name: Deploy (reusable)

on:
  workflow_call:
    inputs:
      module:
        description: "Skaffold module: orion, worker, pusher, emailnotifierjob, memberreconciler, or migrations"
        required: true
        type: string
      environment:
        description: "Target environment: dev or prod"
        required: true
        type: string

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: ${{ inputs.environment }}
    defaults:
      run:
        working-directory: go
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version-file: go/go.mod
          cache-dependency-path: go/go.sum

      - name: Resolve environment settings
        id: env
        run: |
          case "${{ inputs.environment }}" in
            dev)
              echo "project=flowy-dev-440017"  >> "$GITHUB_OUTPUT"
              echo "cluster=cluster"           >> "$GITHUB_OUTPUT"
              ;;
            prod)
              echo "project=flowy-prod-440017" >> "$GITHUB_OUTPUT"
              echo "cluster=prod-cluster"      >> "$GITHUB_OUTPUT"
              ;;
            *)
              echo "Unknown environment: ${{ inputs.environment }}" >&2; exit 1
              ;;
          esac
          echo "region=us-west2" >> "$GITHUB_OUTPUT"

      - name: Run tests
        run: go test ./...

      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v2
        with:
          credentials_json: ${{ inputs.environment == 'prod' && secrets.PROD_GKE_SERVICE_ACCOUNT_KEY || secrets.DEV_GKE_SERVICE_ACCOUNT_KEY }}

      - uses: google-github-actions/setup-gcloud@v2

      - name: Install gke-gcloud-auth-plugin
        run: gcloud components install gke-gcloud-auth-plugin --quiet

      - name: Configure Docker for Artifact Registry
        run: gcloud auth configure-docker us-west2-docker.pkg.dev --quiet

      - name: Get GKE credentials
        run: |
          gcloud container clusters get-credentials "${{ steps.env.outputs.cluster }}" \
            --region "${{ steps.env.outputs.region }}" \
            --project "${{ steps.env.outputs.project }}"

      - name: Install skaffold
        run: |
          curl -fsSLo skaffold https://storage.googleapis.com/skaffold/releases/latest/skaffold-linux-amd64
          sudo install skaffold /usr/local/bin/
          skaffold version

      - name: Deploy
        env:
          SKAFFOLD_DEFAULT_REPO: us-west2-docker.pkg.dev/${{ steps.env.outputs.project }}/deployments
        run: |
          if [ "${{ inputs.module }}" = "migrations" ]; then
            kubectl delete job migrations --ignore-not-found
            skaffold run -p migrations --tail
          else
            skaffold run -p ${{ inputs.environment }} -m ${{ inputs.module }}
          fi
