# Azure Key Vault for secrets management

resource "azurerm_key_vault" "main" {
  name                = var.key_vault_name != "" ? var.key_vault_name : "the-order-kv-${var.environment}"
  location            = var.azure_region
  resource_group_name = azurerm_resource_group.main.name
  tenant_id           = var.tenant_id != "" ? var.tenant_id : data.azurerm_client_config.current.tenant_id

  sku_name = "standard"

  # Network ACLs
  network_acls {
    default_action = "Deny"
    bypass         = "AzureServices"
    ip_rules       = [] # Add allowed IPs for access
  }

  # Enable soft delete and purge protection
  soft_delete_retention_days = 7
  purge_protection_enabled   = var.environment == "prod"

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

# Grant current user/service principal access
resource "azurerm_key_vault_access_policy" "current_user" {
  key_vault_id = azurerm_key_vault.main.id
  tenant_id    = data.azurerm_client_config.current.tenant_id
  object_id    = data.azurerm_client_config.current.object_id

  key_permissions = [
    "Get", "List", "Create", "Delete", "Update", "Import", "Backup", "Restore"
  ]

  secret_permissions = [
    "Get", "List", "Set", "Delete", "Recover", "Backup", "Restore", "Purge"
  ]

  certificate_permissions = [
    "Get", "List", "Create", "Delete", "Update", "Import", "Backup", "Restore"
  ]
}

# Output Key Vault details
output "key_vault_name" {
  value       = azurerm_key_vault.main.name
  description = "Name of the Key Vault"
}

output "key_vault_uri" {
  value       = azurerm_key_vault.main.vault_uri
  description = "URI of the Key Vault"
  sensitive   = true
}

