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
}

variable "postgres_password" {
  type      = string
  sensitive = true
}

module "psql_db" {
  source = "../postgres/tenant"
  
  tenant_name    = "affine"
  admin_username = "postgres"
  admin_password = var.postgres_password
  server_ip      = var.server_ip
  ssh_private_key_path = var.ssh_private_key_path
}

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

  server_ip            = var.server_ip
  ssh_private_key_path = var.ssh_private_key_path

  restart_policy = "never"

  app_name = "affine"
  image    = "ghcr.io/toeverything/affine:stable"
  ports    = ["3020:3010"]
  volumes  = [
    "/opt/storage/data/affine/storage:/root/.affine/storage:Z",
    "/opt/storage/data/affine/config:/root/.affine/config:Z"
  ]
  environment = {
    DATABASE_URL           = "postgresql://affine:${module.psql_db.password}@systemd-postgres:5432/affine"
    REDIS_SERVER_HOST      = "systemd-valkey"
    AFFINE_INDEXER_ENABLED = "false"
  }
  command = [
    "sh",
    "-c",
    "\"node ./scripts/self-host-predeploy.js && node ./dist/main.js\""
  ]
  healthcmd = "curl -f http://localhost:3010 || exit 1"

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

  depends_on_services = ["postgres.service", "valkey.service"]
}

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

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