terraform {
  required_providers {
    fusionauth = {
      source  = "FusionAuth/fusionauth"
      version = "0.1.111"
    }
  }
}
provider "fusionauth" {
  api_key = var.fusionauth_api_key
  host    = var.fusionauth_uri
}

resource "random_password" "client_secret" {
  length  = 32
  special = true
}

resource "fusionauth_application" "app" {
  depends_on = [var.wait_on]

  tenant_id = var.tenant_id
  name      = var.name

  lambda_configuration {
    id_token_populate_id = var.rbac_lambda_id
  }

  oauth_configuration {
    authorized_redirect_urls = [var.oauth_redirect_uri]
    client_secret        = random_password.client_secret.result
    require_registration = var.oauth_require_registration
    enabled_grants       = var.oauth_enabled_grants

    unknown_scope_policy  = "Remove"
    scope_handling_policy = "Strict"

    provided_scope_policy {
      address {
        enabled  = true
        required = false
      }
      phone {
        enabled  = true
        required = false
      }
      email {
        enabled  = true
        required = true
      }
      profile {
        enabled  = true
        required = true
      }
    }
  }
}

resource "fusionauth_application_role" "admin" {
  application_id = fusionauth_application.app.oauth_configuration[0].client_id
  description    = "Admin"
  is_default = true   # NOTE: This is obviously insecure
  is_super_role  = true
  name           = "admin"
}

output "application_id" {
  value = fusionauth_application.app.oauth_configuration[0].client_id
}

output "client_id" {
  value = fusionauth_application.app.oauth_configuration[0].client_id
}

output "client_secret" {
  value     = fusionauth_application.app.oauth_configuration[0].client_secret
  sensitive = true
}

output "redirect_uri" {
  value = var.oauth_redirect_uri
}

output "installed" {
  value = true
  depends_on = [fusionauth_application.app]
}
