variable "wait_on" {
  type        = any
  description = "Resources to wait on"
  default     = true
}

variable "server_ip" {
  type = string
}

variable "ssh_private_key_path" {
  type = string
}

variable "server_domain" {
  type = string
}

# Generate random keys for esign
resource "random_password" "app_id" {
  length  = 12
  special = false
}

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

module "esign" {
  source = "../quadlet-app"
  wait_on = var.wait_on

  server_ip            = var.server_ip
  ssh_private_key_path = var.ssh_private_key_path

  app_name = "esign"
  image    = "docker.io/esign/esignserver:main"
  ports    = ["8180:8080"]
  volumes  = ["/opt/storage/data/esign:/usr/src/app/files:Z"]
  environment = {
    # Node environment
    NODE_ENV = "production"

    # App identifiers
    APP_ID = random_password.app_id.result
    REACT_APP_APPID = random_password.app_id.result
    appName = "Four Lights - eSign"
    MASTER_KEY = random_password.master_key.result

    # Frontend config
    PUBLIC_URL = "https://esign.${var.server_domain}"
    REACT_APP_SERVERURL = "https://esign.${var.server_domain}/api/app"
    GENERATE_SOURCEMAP = "false"

    # Backend API config
    SERVER_URL = "https://esign.${var.server_domain}/api/app"
    PARSE_MOUNT = "/app"

    # MongoDB connection settings
    MONGODB_URI = "mongodb://systemd-documentdb:27017/esign"

    # MinIO/S3 storage configuration
    DO_SPACE = "esign"
    DO_ENDPOINT = "systemd-minio:9000"
    DO_BASEURL = "https://esign.${var.server_domain}/minio"
    DO_ACCESS_KEY_ID = "esign"
    DO_SECRET_ACCESS_KEY = "esign"
    DO_REGION = "us-east-1"

    # Email config (commented out - configure as needed)
    # SMTP_ENABLE = ""
    # SMTP_HOST = ""
    # SMTP_PORT = ""
    # SMTP_USER_EMAIL = ""
    # SMTP_PASS = ""

    # Document signing (optional)
    PFX_BASE64 = ""
    PASS_PHRASE = ""
  }

  haproxy_services = [
    {
      name   = "esign"
      domain = "esign.${var.server_domain}"
      port   = "8180"
      host   = "127.0.0.1"
      tls    = false
    }
  ]
}

output "app_urls" {
  value = module.esign.app_urls
}

output "app_id" {
  value     = random_password.app_id.result
  sensitive = true
}

output "master_key" {
  value     = random_password.master_key.result
  sensitive = true
}

output "installed" {
  value = true
  depends_on = [module.esign.installed]
}
