name: Build and Push to ACR

on:
  push:
    branches: [ dev ]
  workflow_dispatch: {}

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

env:
  AZURE_FEDERATED_TOKEN_FILE: /var/run/secrets/azure/tokens/azure-identity-token

jobs:
  build:
    name: Build and Push
    runs-on: ubuntu-latest
    if: >-
      github.ref != 'refs/heads/main' && (
        github.event_name == 'workflow_dispatch' ||
        (github.event_name == 'push' && github.event.before != '0000000000000000000000000000000000000000')
      )
    permissions:
      contents: read
      id-token: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Install Azure CLI
        run: |
          command -v az &>/dev/null || curl -sL https://aka.ms/InstallAzureCLIDeb | bash

      - name: Install Docker CLI
        run: |
          command -v docker &>/dev/null || (apt-get update -qq && apt-get install -y docker.io)
          docker --version

      - name: Azure login (OIDC)
        run: |
          az login \
            --service-principal \
            --username "$AZURE_CLIENT_ID" \
            --tenant "$AZURE_TENANT_ID" \
            --federated-token "$(cat $AZURE_FEDERATED_TOKEN_FILE)"
          echo "✓ Azure login successful"

      - name: Get ACR details
        run: |
          ACR_NAME=$(az acr list --query "[0].name" -o tsv)
          ACR_NAME="${ACR_NAME:-bstagecjotdevacr}"
          echo "ACR_NAME=$ACR_NAME" >> $GITHUB_ENV
          echo "ACR_LOGIN_SERVER=${ACR_NAME}.azurecr.io" >> $GITHUB_ENV
          echo "✓ Using ACR: ${ACR_NAME}.azurecr.io"

      - name: ACR Login
        run: |
          ACR_TOKEN=$(az acr login --name "$ACR_NAME" --expose-token --output tsv --query accessToken)
          docker login "$ACR_LOGIN_SERVER" \
            --username 00000000-0000-0000-0000-000000000000 \
            --password "$ACR_TOKEN"
          echo "✓ ACR login successful"

      - name: Build and Push Docker image
        run: |
          IMAGE_TAG="${{ gitea.sha }}"
          IMAGE_FULL="${ACR_LOGIN_SERVER}/security-scan-test:${IMAGE_TAG}"
          IMAGE_LATEST="${ACR_LOGIN_SERVER}/security-scan-test:latest"
          docker build -t "$IMAGE_FULL" -t "$IMAGE_LATEST" .
          docker push "$IMAGE_FULL"
          docker push "$IMAGE_LATEST"
          echo "IMAGE_FULL=$IMAGE_FULL" >> $GITHUB_ENV
          echo "✓ Pushed: $IMAGE_FULL"

      - name: Build Summary
        run: |
          echo "### ✅ Build Successful" >> $GITHUB_STEP_SUMMARY
          echo "| | |" >> $GITHUB_STEP_SUMMARY
          echo "|---|---|" >> $GITHUB_STEP_SUMMARY
          echo "| **Service** | security-scan-test |" >> $GITHUB_STEP_SUMMARY
          echo "| **Commit** | ${{ gitea.sha }} |" >> $GITHUB_STEP_SUMMARY
          echo "| **Image** | $IMAGE_FULL |" >> $GITHUB_STEP_SUMMARY
