# Data sources for existing resources
data "azurerm_resource_group" "main" {
  name = var.resource_group_name
}

data "azurerm_kubernetes_cluster" "main" {
  name                = var.aks_cluster_name
  resource_group_name = var.resource_group_name
}

data "azurerm_subscription" "current" {}

# Generate random suffix for unique resource names
resource "random_string" "suffix" {
  length  = 8
  special = false
  upper   = false
}

# Generate random password for PostgreSQL if not provided
resource "random_password" "postgresql_admin_password" {
  count   = var.postgresql_admin_password == null ? 1 : 0
  length  = 32
  special = true
}

# Local variables
locals {
  app_name_safe           = replace(var.app_name, "_", "-")
  postgresql_server_name  = "${local.app_name_safe}-psql-${random_string.suffix.result}"
  postgresql_db_name      = replace(var.app_name, "-", "_")
  postgresql_admin_pass   = var.postgresql_admin_password != null ? var.postgresql_admin_password : random_password.postgresql_admin_password[0].result
  app_url                 = var.app_url != "" ? var.app_url : (var.ingress_host != "" ? "https://${var.ingress_host}" : (var.ingress_enabled ? "http://${try(data.kubernetes_service.ingress_nginx[0].status[0].load_balancer[0].ingress[0].ip, "pending")}" : "ingress-not-enabled"))

  common_labels = {
    app         = var.app_name
    environment = var.app_env
    managed-by  = "terraform"
  }
}
