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 "https" {
  type = bool
  default = false
}

resource "random_password" "minio_access_key" {
  length  = 20
  special = false
}

resource "random_password" "minio_secret_key" {
  length  = 40
  special = false
}

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

  server_ip            = var.server_ip
  ssh_private_key_path = var.ssh_private_key_path

  app_name = "minio"
  image    = "docker.io/minio/minio:latest"
  ports    = [
    "9000:9000",  # API port
    "9001:9001"   # Console port
  ]
  volumes = ["/opt/storage/data/minio:/data:Z"]

  environment = {
    MINIO_ROOT_USER         = random_password.minio_access_key.result
    MINIO_ROOT_PASSWORD     = random_password.minio_secret_key.result
    MINIO_CONSOLE_ADDRESS   = ":9001"
    MINIO_BROWSER_REDIRECT_URL = "${var.https ? "https" : "http" }://storage.${var.server_domain}"
  }

  command = ["server", "/data", "--console-address", ":9001"]
  healthcmd = "curl -f http://localhost:9001/minio/health/live || exit 1"

  # Configure multiple HAProxy services for MinIO
  haproxy_services = [
    {
      name   = "minio_api"
      domain = "storage-api.${var.server_domain}"
      port   = "9000"
      host   = "127.0.0.1"
      tls    = false
    },
    {
      name   = "minio_console"
      domain = "storage.${var.server_domain}"
      port   = "9001"
      host   = "127.0.0.1"
      tls    = false
    }
  ]
}

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

output "server" {
  value = "storage-api.${var.server_domain}"
}

output "access_key" {
  value = random_password.minio_access_key.result
}

output "secret_key" {
  value = random_password.minio_secret_key.result
}

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