#resource "authentik_provider_proxy" "chat" {
#  name          = "Chat"
#  internal_host = "http://open-webui.ollama:8080"
#  external_host = "https://chat.lab.cowley.tech"
#
#  internal_host_ssl_validation = false
#
#  authentication_flow = data.authentik_flow.default-authentication-flow.id
#  authorization_flow  = data.authentik_flow.default-provider-authorization-implicit-consent.id
#  invalidation_flow   = data.authentik_flow.default-provider-invalidation-flow.id
#
#  access_token_validity = "hours=24"
#}
#
#resource "authentik_application" "chat" {
#  name = "Chat"
#  slug = "chat"
#
#  protocol_provider = authentik_provider_proxy.chat.id
#}

resource "random_id" "chat_client_id" {
  byte_length = 16
}
resource "random_id" "chat_secret_key" {
  byte_length = 16
}
resource "authentik_provider_oauth2" "chat" {
  name = "Chat"

  #client_id           = random_id.chat_client_id.id
  client_id           = "2VbXTsFUJV5fgrRJTeQ"
  authentication_flow = data.authentik_flow.default-authentication-flow.id
  authorization_flow  = data.authentik_flow.default-provider-authorization-implicit-consent.id
  invalidation_flow   = data.authentik_flow.default-invalidation-flow.id

  allowed_redirect_uris = [
    {
      "matching_mode" = "strict"
      "url"           = "https://chat.lab.cowley.tech/oauth/oidc/callback"
    }
  ]

  property_mappings = [

    data.authentik_property_mapping_provider_scope.scope-openid.id,
    data.authentik_property_mapping_provider_scope.scope-email.id,
    data.authentik_property_mapping_provider_scope.scope-profile.id,
  ]
  lifecycle {
    ignore_changes = [
      signing_key,
      authentication_flow,
    ]
  }

}

resource "authentik_application" "chat" {
  name              = "Chat"
  slug              = "chat"
  protocol_provider = authentik_provider_oauth2.chat.id
  meta_launch_url   = "https://chat.lab.cowley.tech"
}

resource "kubernetes_secret" "chat" {
  metadata {
    name      = "open-webui-authentik"
    namespace = "ollama"
  }
  data = {
    OAUTH_CLIENT_ID     = authentik_provider_oauth2.chat.client_id
    OAUTH_CLIENT_SECRET = authentik_provider_oauth2.chat.client_secret
    OPENID_PROVIDER_URL = "https://auth.lab.cowley.tech/application/o/chat/.well-known/openid-configuration"
    WEBUI_SECRET_KEY    = random_id.chat_secret_key.hex
  }
}