name: Deploy Staging

on:
  push:
    tags:
      - '*'
  release:
    types:
      - published
  workflow_dispatch:

jobs:
  deploy-frontend:
    if: github.event_name == 'release' || !startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          run_install: false
          package_json_path: package.json

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Build frontend
        run: pnpm --filter=@my-roadtrip/web build
        env:
          VITE_API_URL: ${{ secrets.STAGING_API_URL }}
          VITE_FIREBASE_API_KEY: ${{ secrets.STAGING_FIREBASE_API_KEY }}
          VITE_FIREBASE_AUTH_DOMAIN: ${{ secrets.STAGING_FIREBASE_AUTH_DOMAIN }}
          VITE_FIREBASE_PROJECT_ID: ${{ secrets.STAGING_FIREBASE_PROJECT_ID }}
          VITE_FIREBASE_STORAGE_BUCKET: ${{ secrets.STAGING_FIREBASE_STORAGE_BUCKET }}
          VITE_FIREBASE_MESSAGING_SENDER_ID: ${{ secrets.STAGING_FIREBASE_MESSAGING_SENDER_ID }}
          VITE_FIREBASE_APP_ID: ${{ secrets.STAGING_FIREBASE_APP_ID }}
          VITE_FIREBASE_MEASUREMENT_ID: ${{ secrets.STAGING_FIREBASE_MEASUREMENT_ID }}
          VITE_GOOGLE_MAPS_API_KEY: ${{ secrets.STAGING_GOOGLE_MAPS_API_KEY }}
          VITE_MAPBOX_TOKEN: ${{ secrets.STAGING_MAPBOX_TOKEN }}

      - name: Deploy Firestore rules and indexes
        env:
          FIREBASE_SERVICE_ACCOUNT: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }}
        run: |
          printf '%s' "$FIREBASE_SERVICE_ACCOUNT" > "${HOME}/firebase-service-account.json"
          export GOOGLE_APPLICATION_CREDENTIALS="${HOME}/firebase-service-account.json"
          npx firebase-tools deploy --only firestore:rules,firestore:indexes --project deuxdegamelife --non-interactive
      - name: Deploy to Firebase Hosting (staging)
        uses: FirebaseExtended/action-hosting-deploy@v0
        with:
          repoToken: '${{ secrets.GITHUB_TOKEN }}'
          firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT }}'
          projectId: deuxdegamelife
          channelId: staging
          target: staging

  deploy-backend:
    if: github.event_name == 'release' || !startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: google-github-actions/auth@v2
        with:
          credentials_json: '${{ secrets.GCP_SA_KEY }}'

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

      - name: Build and deploy to Cloud Run
        run: |
          gcloud builds submit \
            --config=cloudbuild.yaml \
            --substitutions=SHORT_SHA=${GITHUB_SHA::7}
