terraform {
  required_providers {
    zitadel = {
      source = "zitadel/zitadel"
    }
  }
}

resource "zitadel_org_idp_google" "default" {
  depends_on = [var.wait_on]
  org_id              = var.org_id
  name                = "Google"
  client_id           = var.client_id
  client_secret       = var.client_secret
  scopes              = var.options.scopes
  is_linking_allowed  = var.options.is_linking_allowed
  is_creation_allowed = var.options.is_creation_allowed
  is_auto_creation    = var.options.is_auto_creation
  is_auto_update      = var.options.is_auto_update
  auto_linking        = var.options.auto_linking
}

resource "zitadel_login_policy" "default" {
  depends_on = [zitadel_org_idp_google.default]

  org_id                        = var.org_id
  user_login                    = false
  allow_register                = true
  allow_external_idp            = true
  force_mfa                     = false
  force_mfa_local_only          = false
  passwordless_type             = "PASSWORDLESS_TYPE_ALLOWED"
  hide_password_reset           = "false"
  password_check_lifetime       = "240h0m0s"
  external_login_check_lifetime = "240h0m0s"
  multi_factor_check_lifetime   = "24h0m0s"
  mfa_init_skip_lifetime        = "720h0m0s"
  second_factor_check_lifetime  = "24h0m0s"
  ignore_unknown_usernames      = true
  default_redirect_uri          = "https://${var.domain}"
  second_factors = ["SECOND_FACTOR_TYPE_OTP", "SECOND_FACTOR_TYPE_U2F"]
  multi_factors = ["MULTI_FACTOR_TYPE_U2F_WITH_VERIFICATION"]
  idps = [zitadel_org_idp_google.default.id]
  allow_domain_discovery        = true
  disable_login_with_email      = true
  disable_login_with_phone      = true
}

#resource "zitadel_action" "verify-email-from-google-idp" {
#  org_id = var.org_id
#  name   = "trustEmailVerification"
#  script = templatefile("${path.module}/verify-email.action.tftpl", {
#    trusted_idp = zitadel_org_idp_google.default.id,
#  })
#  allowed_to_fail = false
#  timeout         = "10s"
#}

#resource "zitadel_trigger_actions" "verify-email-from-google-idp" {
#  org_id       = var.org_id
#  flow_type    = "FLOW_TYPE_EXTERNAL_AUTHENTICATION"
#  trigger_type = "TRIGGER_TYPE_PRE_CREATION"
#  action_ids = [zitadel_action.verify-email-from-google-idp.id]
#}
#
#resource "zitadel_trigger_actions" "internal" {
#  org_id       = var.org_id
#  flow_type    = "FLOW_TYPE_INTERNAL_AUTHENTICATION"
#  trigger_type = "TRIGGER_TYPE_PRE_CREATION"
#  action_ids = [zitadel_action.verify-email-from-google-idp.id]
#}

output "installed" {
  value = true
  depends_on = [
    zitadel_org_idp_google.default, zitadel_login_policy.default,
  ]
}

output "idp_id" {
  value = zitadel_org_idp_google.default.id
}
