terraform {
  required_providers {
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = "2.31.0"
    }
  }
}
resource "random_password" "tenant" {
  length           = 24
  special          = true
  override_special = "!#$%&*()-_=+[]{}<>:?"
  min_special      = 2
  min_upper        = 2
  min_lower        = 2
  min_numeric      = 2
}

resource "kubernetes_job" "create-tenant" {
  count = var.enabled ? 1 : 0
  depends_on = [var.wait_on]

  metadata {
    name      = "create-tenant-${var.name}"
    namespace = var.namespace
  }

  spec {
    template {
      metadata {}
      spec {
        container {
          name  = "create-db-user"
          image = "postgres:17-alpine"
          command = ["/bin/sh", "-c"]
          args = [
            <<-EOF
              # Wait for postgres to be ready
              until PGPASSWORD=$ROOT_PASSWORD psql -h $POSTGRES_HOST -U $ROOT_USERNAME -d $ROOT_DATABASE -c '\l'; do
                echo "Waiting for postgres..."
                sleep 2
              done

              # Create user and database
              PGPASSWORD=$ROOT_PASSWORD psql -v ON_ERROR_STOP=1 -h $POSTGRES_HOST -U $ROOT_USERNAME -d $ROOT_DATABASE <<-EOSQL
                CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';
                CREATE DATABASE $DB_NAME OWNER $DB_USER;
                GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
              EOSQL
            EOF
          ]

          env {
            name  = "POSTGRES_HOST"
            value = var.host
          }

          env {
            name  = "ROOT_USERNAME"
            value = var.root_username
          }

          env {
            name  = "ROOT_PASSWORD"
            value = var.root_password
          }

          env {
            name  = "ROOT_DATABASE"
            value = var.root_database
          }

          env {
            name  = "DB_NAME"
            value = var.name
          }

          env {
            name  = "DB_USER"
            value = var.name
          }

          env {
            name  = "DB_PASSWORD"
            value = random_password.tenant.result
          }
        }
      }
    }
  }
}

output "installed" {
  value = true
  depends_on = [kubernetes_job.create-tenant]
}

output "password" {
  value     = random_password.tenant.result
  sensitive = true
}

output "database" {
  value = var.name
}

output "username" {
  value = var.name
}

output "job_name" {
  value = var.enabled ? kubernetes_job.create-tenant[0].metadata[0].name : null
}
