# Azure Database for PostgreSQL
# Flexible Server for production workloads

variable "database_name" {
  description = "PostgreSQL database name"
  type        = string
  default     = ""
}

variable "database_admin_user" {
  description = "PostgreSQL admin username"
  type        = string
  default     = "theorder_admin"
}

variable "database_sku_name" {
  description = "PostgreSQL SKU (e.g., Standard_B1ms, Standard_B2s)"
  type        = string
  default     = "Standard_B1ms"
}

variable "database_storage_mb" {
  description = "PostgreSQL storage in MB"
  type        = number
  default     = 32768  # 32 GB
}

resource "azurerm_postgresql_flexible_server" "main" {
  name                   = var.database_name != "" ? var.database_name : "the-order-db-${var.environment}"
  resource_group_name    = azurerm_resource_group.main.name
  location               = var.azure_region
  version                = "15"
  delegated_subnet_id    = null  # Set if using VNet integration
  private_dns_zone_id    = null  # Set if using private DNS
  administrator_login    = var.database_admin_user
  administrator_password = null  # Set via Key Vault secret
  zone                   = "1"

  storage_mb  = var.database_storage_mb
  sku_name    = var.database_sku_name

  backup {
    geo_redundant_backup_enabled = var.environment == "prod"
    backup_retention_days        = var.environment == "prod" ? 35 : 7
  }

  high_availability {
    mode                      = var.environment == "prod" ? "ZoneRedundant" : "Disabled"
    standby_availability_zone = var.environment == "prod" ? "2" : null
  }

  maintenance_window {
    day_of_week  = 0  # Sunday
    start_hour   = 2
    start_minute = 0
  }

  tags = merge(var.tags, {
    Purpose = "Database"
  })
}

# Database
resource "azurerm_postgresql_flexible_server_database" "main" {
  count     = var.create_database ? 1 : 0
  name      = "theorder_${var.environment}"
  server_id = azurerm_postgresql_flexible_server.main[0].id
  charset   = "UTF8"
  collation = "en_US.utf8"
}

# Firewall rules - allow Azure services
resource "azurerm_postgresql_flexible_server_firewall_rule" "azure_services" {
  count            = var.create_database ? 1 : 0
  name             = "AllowAzureServices"
  server_id        = azurerm_postgresql_flexible_server.main[0].id
  start_ip_address = "0.0.0.0"
  end_ip_address   = "0.0.0.0"
}

# Generate random password for database
resource "random_password" "database_password" {
  count   = var.create_database ? 1 : 0
  length  = 32
  special = true
}

# Store database connection string in Key Vault
resource "azurerm_key_vault_secret" "database_url" {
  count        = var.create_database ? 1 : 0
  name         = "database-url"
  value        = "postgresql://${var.database_admin_user}:${random_password.database_password[0].result}@${azurerm_postgresql_flexible_server.main[0].fqdn}:5432/${azurerm_postgresql_flexible_server_database.main[0].name}?sslmode=require"
  key_vault_id = azurerm_key_vault.main.id

  tags = var.tags
}

# Store password in Key Vault
resource "azurerm_key_vault_secret" "database_password" {
  count        = var.create_database ? 1 : 0
  name         = "database-password"
  value        = random_password.database_password[0].result
  key_vault_id = azurerm_key_vault.main.id

  tags = var.tags
}

# Outputs
output "database_fqdn" {
  value       = var.create_database ? azurerm_postgresql_flexible_server.main[0].fqdn : null
  description = "Fully qualified domain name of the database server"
  sensitive   = true
}

output "database_name" {
  value       = var.create_database ? azurerm_postgresql_flexible_server_database.main[0].name : null
  description = "Name of the database"
}

