name: CD (Manual Deploy to Cloud Run)

on:
  workflow_dispatch:

env:
  PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }}
  GAR_LOCATION: ${{ secrets.GAR_LOCATION }}
  REPOSITORY: ${{ secrets.GAR_REPOSITORY }}
  SERVICE: ${{ secrets.CLOUD_RUN_SERVICE }}
  REGION: ${{ secrets.GCP_REGION }}

jobs:
  deploy:
    runs-on: ubuntu-latest

    permissions:
      contents: read
      id-token: write

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

      - name: Google Auth (WIF)
        id: auth
        uses: google-github-actions/auth@v2
        with:
          token_format: "access_token"
          workload_identity_provider: ${{ secrets.WIF_PROVIDER }}
          service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}

      - name: Artifact Registry Docker Login
        uses: docker/login-action@v3
        with:
          registry: ${{ env.GAR_LOCATION }}-docker.pkg.dev
          username: "oauth2accesstoken"
          password: ${{ steps.auth.outputs.access_token }}

      - name: Build & Push Docker Image
        env:
          IMAGE: ${{ env.GAR_LOCATION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.SERVICE }}:${{ github.sha }}
        run: |
          docker build -t "$IMAGE" .
          docker push "$IMAGE"

      - name: Deploy to Cloud Run
        id: deploy
        uses: google-github-actions/deploy-cloudrun@v2
        with:
          service: ${{ env.SERVICE }}
          region: ${{ env.REGION }}
          image: ${{ env.GAR_LOCATION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.SERVICE }}:${{ github.sha }}

      - name: Deployment URL
        run: echo "🚀 Deployed → ${{ steps.deploy.outputs.url }}"
