name: Deploy Frontend to Staging

# Triggered on every push to main.
# Syncs this repo's source into the backend monorepo's frontend/
# directory and rebuilds the encoach-frontend Docker container.
on:
  push:
    branches: [main]

concurrency:
  group: deploy-frontend
  cancel-in-progress: true

jobs:
  deploy:
    name: Deploy frontend to staging
    runs-on: self-hosted

    steps:
      - name: Sync frontend source to backend repo
        run: |
          FRONTEND_SRC="/opt/encoach/encoach_frontend_new_v2"
          FRONTEND_DEST="/opt/encoach/encoach_backend_new_v2/frontend"

          # Keep a clean clone of this repo on the server
          if [ -d "$FRONTEND_SRC/.git" ]; then
            git -C "$FRONTEND_SRC" fetch origin
            git -C "$FRONTEND_SRC" reset --hard origin/main
          else
            git clone http://localhost:3003/devops/encoach_frontend_new_v2.git "$FRONTEND_SRC"
          fi

          echo "Syncing to backend frontend/ dir..."
          rsync -a --delete \
            --exclude '.git' \
            --exclude 'node_modules' \
            --exclude 'dist' \
            --exclude 'docs' \
            "$FRONTEND_SRC/" "$FRONTEND_DEST/"
          echo "Latest commit: $(git -C $FRONTEND_SRC log -1 --oneline)"

      - name: Rebuild frontend container
        run: |
          cd /opt/encoach/encoach_backend_new_v2
          docker compose \
            -f docker-compose.yml \
            -f /opt/encoach/overrides/encoach.override.yml \
            up -d --build frontend
          docker ps --format "table {{.Names}}\t{{.Status}}" | grep encoach-frontend

      - name: Smoke test
        run: |
          sleep 5
          STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/)
          echo "frontend / => HTTP $STATUS"
          test "$STATUS" = "200" || exit 1
          echo "Deploy successful!"
