pipeline {
  agent any
  environment {
    // Fetch the ACR login server from Terraform outputs
    ACR_LOGIN_SERVER = sh(script: 'terraform output -raw container_registry_url', returnStdout: true).trim()
    RESOURCE_GROUP   = 'Prod-Native-American-Empires'
    CONTAINER_APP    = 'skennen'
  }
  stages {
    stage('Checkout') {
      steps {
        checkout scm
      }
    }
    stage('Build Docker Image') {
      steps {
        sh '''
          docker build -t skennen:${BUILD_NUMBER} \
            -f dotnet8-minimal-api/Dockerfile dotnet8-minimal-api
        '''
      }
    }
    stage('Tag & Push to ACR') {
      steps {
        withCredentials([usernamePassword(
          credentialsId: 'acr-creds',
          usernameVariable: 'ACR_USER',
          passwordVariable: 'ACR_PASS')]) {
          sh '''
            docker login $ACR_LOGIN_SERVER -u $ACR_USER -p $ACR_PASS
            docker tag skennen:${BUILD_NUMBER} $ACR_LOGIN_SERVER/skennen:${BUILD_NUMBER}
            docker tag skennen:${BUILD_NUMBER} $ACR_LOGIN_SERVER/skennen:latest
            docker push $ACR_LOGIN_SERVER/skennen:${BUILD_NUMBER}
            docker push $ACR_LOGIN_SERVER/skennen:latest
          '''
        }
      }
    }
    stage('Deploy to Container App') {
      steps {
        withCredentials([
          string(credentialsId: 'azure-subscription-id', variable: 'AZ_SUB'),
          string(credentialsId: 'azure-client-id', variable: 'AZ_CLIENT_ID'),
          string(credentialsId: 'azure-client-secret', variable: 'AZ_CLIENT_SECRET'),
          string(credentialsId: 'azure-tenant-id', variable: 'AZ_TENANT_ID')
        ]) {
          sh '''
            echo "Logging in to Azure..."
            az login --service-principal -u $AZ_CLIENT_ID -p $AZ_CLIENT_SECRET --tenant $AZ_TENANT_ID
            echo "Setting subscription..."
            az account set --subscription $AZ_SUB
            echo "Updating container app..."
            az containerapp update \
              --name $CONTAINER_APP \
              --resource-group $RESOURCE_GROUP \
              --image $ACR_LOGIN_SERVER/skennen:latest
          '''
        }
      }
    }
  }
  post {
    always {
      cleanWs()
    }
  }
}