name: CD API
on:
  push:
    branches: [ main, master ]
    paths:
      - "backend/api/package.json"
      - ".github/workflows/cd-api.yml"

jobs:
  deploy:
    name: Deploy
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0    # we need full history for git log

      - name: Install jq
        run: sudo apt-get install -y jq

      - name: Read current version
        id: current
        run: |
          current=$(jq -r '.version' backend/api/package.json)
          echo "version=$current" >> $GITHUB_OUTPUT

      - name: Read previous version
        id: previous
        run: |
          # Get previous commit’s package.json (if it existed)
          if git show HEAD^:backend/api/package.json >/dev/null 2>&1; then
            previous=$(git show HEAD^:backend/api/package.json | jq -r '.version')
          else
            previous="none"
          fi
          echo "version=$previous" >> $GITHUB_OUTPUT

      - name: Check version change
        id: check
        run: |
          echo "current=${{ steps.current.outputs.version }}"
          echo "previous=${{ steps.previous.outputs.version }}"
          if [ "${{ steps.current.outputs.version }}" = "${{ steps.previous.outputs.version }}" ]; then
            echo "changed=false" >> $GITHUB_OUTPUT
          else
            echo "changed=true" >> $GITHUB_OUTPUT
          fi

      - name: Setup Node.js
        if: steps.check.outputs.changed == 'true'
        uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install dependencies
        if: steps.check.outputs.changed == 'true'
        run: yarn install

      - name: Authenticate to GCP
        if: steps.check.outputs.changed == 'true'
        uses: google-github-actions/auth@v2
        with:
          credentials_json: ${{ secrets.GCP_SA_KEY }}

      - name: Install gcloud CLI
        if: steps.check.outputs.changed == 'true'
        uses: google-github-actions/setup-gcloud@v2
        with:
          project_id: compass-130ba

      - name: Configure Docker for Artifact Registry
        if: steps.check.outputs.changed == 'true'
        run: |
          gcloud auth configure-docker us-west1-docker.pkg.dev --quiet

      - name: Install Tofu (Terraform)
        if: steps.check.outputs.changed == 'true'
        run: |
          sudo apt-get update
          sudo apt-get install -y wget unzip
          LATEST=https://github.com/opentofu/opentofu/releases/download/v1.10.5/tofu_1.10.5_linux_amd64.zip
          curl -LO "$LATEST"
          unzip -o tofu_*_linux_amd64.zip
          sudo mv tofu /usr/local/bin/
          rm tofu_*_linux_amd64.zip
          echo "OpenTofu version: $(tofu version)"
          cd backend/api || exit 1
          tofu init

      - name: Run deploy script
        if: steps.check.outputs.changed == 'true'
        run: |
          chmod +x backend/api/deploy-api.sh
          backend/api/deploy-api.sh
