// Deployment inputs
// Deploy into the selected resource group. Use location for the region and stem for the name prefix.
targetScope = 'resourceGroup'
param location string
@minLength(9)
@maxLength(14)
param stem string
// Use the signed-in Entra user's object ID for the role assignments below.
param operatorId string

// Pass false to create the AKS and Products identities. The default also creates the worker identities.
param includeWorkerIdentities bool = true
var identityNames = concat(['cluster', 'products'], includeWorkerIdentities ? ['embedder', 'chat'] : [])

// Network and private DNS
// AKS, Functions, and PostgreSQL use separate subnets. The NAT gateway uses a static IP for outbound
// traffic. The linked DNS zone lets workloads on the virtual network resolve PostgreSQL's private name.
resource egressIp 'Microsoft.Network/publicIPAddresses@2026-03-01' = {
  name: '${stem}-egress'
  location: location
  sku: { name: 'Standard' }
  properties: { publicIPAllocationMethod: 'Static' }
}
resource nat 'Microsoft.Network/natGateways@2026-03-01' = {
  name: '${stem}-nat'
  location: location
  sku: { name: 'Standard' }
  properties: { publicIpAddresses: [{ id: egressIp.id }], idleTimeoutInMinutes: 10 }
}
resource network 'Microsoft.Network/virtualNetworks@2026-03-01' = {
  name: '${stem}-vnet'
  location: location
  properties: {
    addressSpace: { addressPrefixes: ['10.70.0.0/16'] }
    subnets: [
      { name: 'aks', properties: { addressPrefix: '10.70.0.0/22', defaultOutboundAccess: false, natGateway: { id: nat.id } } }
      {
        name: 'functions'
        properties: {
          addressPrefix: '10.70.8.0/24'
          defaultOutboundAccess: false
          natGateway: { id: nat.id }
          delegations: [{ name: 'flex', properties: { serviceName: 'Microsoft.App/environments' } }]
        }
      }
      {
        name: 'postgres'
        properties: {
          addressPrefix: '10.70.9.0/24'
          natGateway: { id: nat.id }
          delegations: [{ name: 'postgres', properties: { serviceName: 'Microsoft.DBforPostgreSQL/flexibleServers' } }]
        }
      }
    ]
  }
}
resource dns 'Microsoft.Network/privateDnsZones@2024-06-01' = {
  name: '${stem}.postgres.database.azure.com'
  location: 'global'
}
resource link 'Microsoft.Network/privateDnsZones/virtualNetworkLinks@2024-06-01' = {
  parent: dns
  name: 'workshop'
  location: 'global'
  properties: { registrationEnabled: false, virtualNetwork: { id: network.id } }
}

// Managed identities
// AKS uses its identity to manage the network. Each app gets its own identity for access to Azure services.
resource identities 'Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30' = [for suffix in identityNames: {
  name: '${stem}-${suffix}'
  location: location
}]
resource networkRole 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  // AKS must read/use both the VNet and its separate NAT/public-IP resources.
  // Keep this network-management role inside the workshop resource group.
  name: guid(resourceGroup().id, identities[0].id, 'network')
  properties: {
    principalId: identities[0].properties.principalId
    principalType: 'ServicePrincipal'
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4d97b98b-1d4f-4787-a291-c67834d212e7')
  }
}

// Container registry
// Push the Products image here so AKS can pull it when the app starts.
resource acr 'Microsoft.ContainerRegistry/registries@2025-11-01' = {
  name: '${stem}acr'
  location: location
  sku: { name: 'Basic' }
  properties: { adminUserEnabled: false }
}

// Blob Storage for uploads
// Products writes uploads to the private manuals container. ProductsEmbedder reads them when indexing.
resource storage 'Microsoft.Storage/storageAccounts@2026-09-01' = {
  name: '${stem}st'
  location: location
  kind: 'StorageV2'
  sku: { name: 'Standard_LRS' }
  properties: {
    allowBlobPublicAccess: false
    allowSharedKeyAccess: false
    minimumTlsVersion: 'TLS1_2'
    supportsHttpsTrafficOnly: true
  }
}
resource blobService 'Microsoft.Storage/storageAccounts/blobServices@2026-09-01' = { parent: storage, name: 'default' }
resource manuals 'Microsoft.Storage/storageAccounts/blobServices/containers@2026-09-01' = {
  parent: blobService
  name: 'manuals'
  properties: { publicAccess: 'None' }
}

// Secrets and settings
// Use Key Vault for passwords and App Configuration for service endpoints and other settings.
resource vault 'Microsoft.KeyVault/vaults@2026-05-15' = {
  name: '${stem}-kv'
  location: location
  properties: {
    tenantId: tenant().tenantId
    sku: { family: 'A', name: 'standard' }
    enableRbacAuthorization: true
    enableSoftDelete: true
    softDeleteRetentionInDays: 7
    accessPolicies: []
  }
}
resource config 'Microsoft.AppConfiguration/configurationStores@2024-06-01' = {
  name: '${stem}-cfg'
  location: location
  sku: { name: 'standard' }
  properties: { disableLocalAuth: true, softDeleteRetentionInDays: 1, enablePurgeProtection: false }
}

// Operator access
// Let the Entra user manage secrets and settings and read blobs. Scope each role to its own resource.
resource vaultOperator 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(vault.id, operatorId, 'secrets-officer')
  scope: vault
  properties: {
    principalId: operatorId
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b86a8fe4-44ce-4948-aee5-eccb2c155cd7')
  }
}
resource configOperator 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(config.id, operatorId, 'config-owner')
  scope: config
  properties: {
    principalId: operatorId
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '5ae67dd6-50cb-40e7-96ff-dc2bfa4b606b')
  }
}
resource storageInspector 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(storage.id, operatorId, 'blob-reader')
  scope: storage
  properties: {
    principalId: operatorId
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '2a2b9908-6ea1-4ae2-8e65-a410df84e7d1')
  }
}

// Deployment outputs
// Azure records these IDs and the endpoint with the deployment.
// Use configEndpoint to fill APP_CONFIG_ENDPOINT in the Products manifest.
output identities array = [for (suffix, i) in identityNames: {
  name: suffix
  id: identities[i].id
  clientId: identities[i].properties.clientId
  principalId: identities[i].properties.principalId
}]
output networkId string = network.id
output storageId string = storage.id
output configEndpoint string = config.properties.endpoint
