import { Environment, EnvironmentVar } from '../types.bicep'

param environment Environment
param location string
param containerAppName string
param containerImage string
param containerPort int
param minReplicas int = environment == 'prod' ? 2 : 1
param maxReplicas int = 15
param pollingInterval int = 5
param envVars EnvironmentVar[] = []
param userAssignedIdentityId string

resource acr 'Microsoft.ContainerRegistry/registries@2023-07-01' existing = {
  name: 'acrscandicfrontend'
  scope: resourceGroup('1e6ef69e-8719-4924-a311-e66fe00399c7', 'rg-shared')
}

resource containerApp 'Microsoft.App/containerApps@2024-10-02-preview' = {
  name: containerAppName
  location: location
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${userAssignedIdentityId}': {}
    }
  }
  properties: {
    environmentId: resourceId('Microsoft.App/managedEnvironments', 'cae-redis-api-${environment}')
    configuration: {
      activeRevisionsMode: 'Single'
      registries: [
        {
          identity: userAssignedIdentityId
          server: acr.properties.loginServer
        }
      ]
      ingress: {
        external: true
        targetPort: containerPort
      }
    }
    template: {
      containers: [
        {
          name: containerAppName
          image: containerImage
          imageType: 'ContainerImage'
          env: [
            for envVar in envVars: {
              name: envVar.name
              value: envVar.value
            }
          ]
          probes: [
            {
              type: 'Liveness'
              httpGet: {
                port: containerPort
                path: '/health'
              }
            }
          ]
          resources: {
            cpu: json('0.5')
            memory: '1.0Gi'
          }
        }
      ]
      scale: {
        minReplicas: minReplicas
        maxReplicas: maxReplicas
        pollingInterval: pollingInterval
        rules: [
          {
            name: 'http-rule'
            http: {
              metadata: {
                concurrentRequests: '100'
              }
            }
          }
          {
            name: 'cpu-scaler'
            custom: {
              type: 'cpu'
              metadata: {
                type: 'Utilization'
                value: '70' // Trigger scaling if CPU > 70%
              }
            }
          }
          {
            name: 'memory-scaler'
            custom: {
              type: 'memory'
              metadata: {
                type: 'Utilization'
                value: '75' // Scale up if memory usage > 75%
              }
            }
          }
        ]
      }
    }
  }
}
