locals {
  argocd_uri = "https://${var.argocd_service_domain}"
}

module "zitadel_project" {
  source = "../../../modules/zitadel/project"

  org_id = var.org_id
  name   = var.name
  owners = [var.user_id]
}

module "zitadel_project_roles_user" {
  source = "../../../modules/zitadel/project/roles"

  org_id     = var.org_id
  project_id = module.zitadel_project.project_id
  group      = "Users"
  roles = ["user"]
}

module "zitadel_project_roles_admin" {
  source = "../../../modules/zitadel/project/roles"

  org_id     = var.org_id
  project_id = module.zitadel_project.project_id
  group      = "Admins"
  roles = ["admin"]
}

module "zitadel_application_argocd" {
  source = "../../../modules/zitadel/project/application/web"

  name       = "ArgoCD"
  org_id     = var.org_id
  project_id = module.zitadel_project.project_id

  redirect_uris = ["${ local.argocd_uri}/api/dex/callback"]
  post_logout_redirect_uris = [local.argocd_uri]

  auth_method_type            = "OIDC_AUTH_METHOD_TYPE_BASIC"
  id_token_role_assertion     = true
  id_token_userinfo_assertion = true
}

resource "zitadel_action" "groups-claim" {
  org_id          = var.org_id
  name            = "groupsClaim"
  script = templatefile("${path.module}/groupsClaim.action.tftpl", {})
  allowed_to_fail = true
  timeout         = "10s"
}

resource "zitadel_trigger_actions" "groups-claim-pre-user-info" {
  org_id       = var.org_id
  flow_type    = "FLOW_TYPE_CUSTOMISE_TOKEN"
  trigger_type = "TRIGGER_TYPE_PRE_USERINFO_CREATION"
  action_ids = [zitadel_action.groups-claim.id]
}

resource "zitadel_trigger_actions" "groups-claim-pre-access-token" {
  org_id       = var.org_id
  flow_type    = "FLOW_TYPE_CUSTOMISE_TOKEN"
  trigger_type = "TRIGGER_TYPE_PRE_ACCESS_TOKEN_CREATION"
  action_ids = [zitadel_action.groups-claim.id]
}

module "zitadel_project_user_grant" {
  source = "../../../modules/zitadel/project/user-grant"

  org_id = var.org_id

  project_id = module.zitadel_project.project_id
  user_id    = var.user_id

  roles = module.zitadel_project_roles_admin.roles
}

output "client_id" {
  value = module.zitadel_application_argocd.client_id
}

output "client_secret" {
  value = module.zitadel_application_argocd.client_secret
}

output "scopes" {
  value = ["openid", "profile", "email", "groups"]
}

output "logoutSuffix" {
  value = "oidc/v1/end_session"
}

output "user_roles" {
  value = module.zitadel_project_roles_user.roles
}

output "admin_roles" {
  value = module.zitadel_project_roles_admin.roles
}

output "project_id" {
  value = module.zitadel_project.project_id
}

output "installed" {
  value = true
  depends_on = [
    module.zitadel_project_user_grant.installed,
    zitadel_trigger_actions.groups-claim-pre-access-token, zitadel_trigger_actions.groups-claim-pre-user-info
  ]
}
