# Azure Database for PostgreSQL Flexible Server
resource "azurerm_postgresql_flexible_server" "main" {
  name                = local.postgresql_server_name
  resource_group_name = data.azurerm_resource_group.main.name
  location            = var.location

  administrator_login    = var.postgresql_admin_username
  administrator_password = local.postgresql_admin_pass

  sku_name   = var.postgresql_sku_name
  version    = var.postgresql_version
  storage_mb = var.postgresql_storage_mb

  backup_retention_days        = var.postgresql_backup_retention_days
  geo_redundant_backup_enabled = false

  # Public access for initial setup (can be restricted later)
  # For production, consider using private endpoints or VNet integration
  public_network_access_enabled = true

  zone = "1"

  tags = merge(
    local.common_labels,
    {
      purpose = "database"
    }
  )
}

# PostgreSQL Firewall Rule - Allow Azure Services
resource "azurerm_postgresql_flexible_server_firewall_rule" "allow_azure_services" {
  name             = "AllowAzureServices"
  server_id        = azurerm_postgresql_flexible_server.main.id
  start_ip_address = "0.0.0.0"
  end_ip_address   = "0.0.0.0"
}

# PostgreSQL Firewall Rule - Allow AKS Outbound IPs
# Note: In production, consider using VNet integration or private endpoints
resource "azurerm_postgresql_flexible_server_firewall_rule" "allow_all_temporary" {
  name             = "AllowAllTemporary"
  server_id        = azurerm_postgresql_flexible_server.main.id
  start_ip_address = "0.0.0.0"
  end_ip_address   = "255.255.255.255"

  # This is a temporary rule for initial setup
  # Replace with specific IP ranges or VNet integration in production
}

# PostgreSQL Database
resource "azurerm_postgresql_flexible_server_database" "main" {
  name      = local.postgresql_db_name
  server_id = azurerm_postgresql_flexible_server.main.id
  collation = "en_US.utf8"
  charset   = "utf8"
}

# PostgreSQL Configuration - Optimize for Laravel
resource "azurerm_postgresql_flexible_server_configuration" "max_connections" {
  name      = "max_connections"
  server_id = azurerm_postgresql_flexible_server.main.id
  value     = "200"
}

resource "azurerm_postgresql_flexible_server_configuration" "timezone" {
  name      = "timezone"
  server_id = azurerm_postgresql_flexible_server.main.id
  value     = "UTC"
}
