name: Deploy Entra VerifiedID to Staging

on:
  push:
    branches:
      - develop
    paths:
      - 'services/identity/**'
      - 'packages/auth/**'
      - 'infra/k8s/**'
  workflow_dispatch:

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}/identity-service

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

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

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./services/identity/Dockerfile
          push: true
          tags: |
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:staging-${{ github.sha }}
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:staging-latest
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Set up kubectl
        uses: azure/setup-kubectl@v3

      - name: Configure kubectl
        run: |
          echo "${{ secrets.KUBECONFIG_STAGING }}" | base64 -d > kubeconfig
          export KUBECONFIG=kubeconfig

      - name: Deploy to staging
        run: |
          export KUBECONFIG=kubeconfig
          export IMAGE_TAG=staging-${{ github.sha }}
          export BUILD_IMAGE=false
          ./scripts/deploy/deploy-staging.sh

      - name: Verify deployment
        run: |
          export KUBECONFIG=kubeconfig
          kubectl rollout status deployment/identity-service -n the-order-staging --timeout=5m

      - name: Run smoke tests
        run: |
          export KUBECONFIG=kubeconfig
          STAGING_URL="https://api-staging.theorder.org"
          curl -f "${STAGING_URL}/health" || exit 1
          echo "Smoke tests passed"

