resource "random_id" "chat_client_id" {
  byte_length = 16
}

resource "authentik_provider_oauth2" "chat" {
  name = "Chat"
  #  Required. You can use the output of:
  #     $ openssl rand -hex 16
  client_id = random_id.chat_client_id.id

  # Optional: will be generated if not provided
  # client_secret = "my_client_secret"

  authorization_flow = data.authentik_flow.default-provider-authorization-implicit-consent.id

  redirect_uris = [
    "https://chat.lab.cowley.tech/oauth/oidc/callback"
  ]
  property_mappings = [
    data.authentik_scope_mapping.scope-openid.id,
    data.authentik_scope_mapping.scope-email.id,
    data.authentik_scope_mapping.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
}

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"
    OAUTH_PROVIDER_NAME = "Authentik"
    OAUTH_SCOPES        = "openid email profile"
  }
}