# GitHub Actions workflow for deploying Gateway to Google Cloud Run
# Documentation: https://cloud.google.com/run/docs/deploying
#
# Required GitHub Secrets:
#   - GCP_PROJECT_ID: Your Google Cloud Project ID
#   - GCP_SA_KEY: Service Account JSON key with Cloud Run Admin and Cloud Build Editor roles
#   - GCP_SERVICE_ACCOUNT_EMAIL: Email of the service account to run Cloud Run service as
#
# Required Google Cloud Setup:
#   1. Create a service account with Cloud Run Admin and Cloud Build Editor roles
#   2. Create secret "CONFIG_KEY" in Secret Manager with your master key
#   3. Grant the service account access to Secret Manager secrets
#   4. Create Cloud SQL instance (if not exists)
#   5. Create env_prod.env and env_int.env files with your configuration
#
# Environment Selection:
#   - Push to 'main' branch → uses env_prod.env (production)
#   - Push to 'int' branch → uses env_int.env (integration)
#   - Manual dispatch → select environment (prod/int) to use corresponding env file

name: Deploy Gateway to Google Cloud Run

on:
  push:
    branches:
      - main
      - int
    paths:
      - 'gateway/**'
  workflow_dispatch:
    inputs:
      environment:
        description: 'Environment to deploy to'
        required: true
        default: 'prod'
        type: choice
        options:
          - prod
          - int

# Cancel in-progress runs when a new run is triggered (saves logs/storage)
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

env:
  PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }}
  REGION: europe-west6  # Zurich region

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write  # Required for Workload Identity Federation

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

      - name: Determine environment
        id: env
        run: |
          if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
            ENV_TYPE="${{ github.event.inputs.environment }}"
          elif [ "${{ github.ref }}" == "refs/heads/int" ]; then
            ENV_TYPE="int"
          else
            ENV_TYPE="prod"
          fi
          echo "env_type=$ENV_TYPE" >> $GITHUB_OUTPUT
          echo "service_name=gateway-$ENV_TYPE" >> $GITHUB_OUTPUT
          echo "env_file=env_${ENV_TYPE}.env" >> $GITHUB_OUTPUT
          echo "Determined environment: $ENV_TYPE"
          echo "Service name: gateway-$ENV_TYPE"
          echo "Env file: env_${ENV_TYPE}.env"

      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v2
        with:
          credentials_json: ${{ secrets.GCP_SA_KEY }}
          # Alternative: Use Workload Identity Federation (more secure)
          # workload_identity_provider: ${{ secrets.WIF_PROVIDER }}
          # service_account: ${{ secrets.WIF_SERVICE_ACCOUNT }}

      - name: Set up Cloud SDK
        uses: google-github-actions/setup-gcloud@v2

      - name: Configure Docker for GCR
        run: |
          gcloud auth configure-docker

      - name: Set environment file
        run: |
          cd gateway
          ENV_FILE="${{ steps.env.outputs.env_file }}"
          if [ -f "$ENV_FILE" ]; then
            echo "Using $ENV_FILE"
            cp "$ENV_FILE" .env
          else
            echo "Warning: $ENV_FILE not found, using env_prod.env as fallback"
            cp env_prod.env .env
          fi
          # Clean up other env files (optional, for security)
          rm -f env_*.env

      - name: Build and push container image
        working-directory: ./gateway
        run: |
          # Build container image using Cloud Build
          # If Dockerfile exists, it will be used; otherwise Cloud Buildpacks will be used
          SERVICE_NAME="${{ steps.env.outputs.service_name }}"
          gcloud builds submit \
            --tag gcr.io/${{ env.PROJECT_ID }}/$SERVICE_NAME:${{ github.sha }} \
            --tag gcr.io/${{ env.PROJECT_ID }}/$SERVICE_NAME:latest \
            --project ${{ env.PROJECT_ID }}

      - name: Deploy to Cloud Run
        run: |
          SERVICE_NAME="${{ steps.env.outputs.service_name }}"
          ENV_TYPE="${{ steps.env.outputs.env_type }}"
          gcloud run deploy $SERVICE_NAME \
            --image gcr.io/${{ env.PROJECT_ID }}/$SERVICE_NAME:${{ github.sha }} \
            --region ${{ env.REGION }} \
            --platform managed \
            --allow-unauthenticated \
            --project ${{ env.PROJECT_ID }} \
            --set-env-vars "APP_ENV_TYPE=$ENV_TYPE" \
            --set-secrets "CONFIG_KEY=CONFIG_KEY:latest" \
            --memory 2Gi \
            --cpu 2 \
            --timeout 300 \
            --max-instances 10 \
            --min-instances 1 \
            --port 8000 \
            --service-account ${{ secrets.GCP_SERVICE_ACCOUNT_EMAIL }}

      - name: Get service URL
        id: service-url
        run: |
          SERVICE_NAME="${{ steps.env.outputs.service_name }}"
          SERVICE_URL=$(gcloud run services describe $SERVICE_NAME \
            --region ${{ env.REGION }} \
            --project ${{ env.PROJECT_ID }} \
            --format 'value(status.url)')
          echo "url=$SERVICE_URL" >> $GITHUB_OUTPUT

      - name: Output deployment URL
        run: |
          echo "🚀 Deployment successful!"
          echo "Service URL: ${{ steps.service-url.outputs.url }}"
