name: CI/CD — Build & Deploy

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build-and-deploy:
    name: Build & Deploy
    runs-on: vps-runner

    steps:
      - uses: actions/checkout@v4

      # ── Backend ──────────────────────────────────────────────────────────────
      - name: Install & build backend
        run: |
          npm ci
          npm run build

      - name: Deploy backend
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        run: |
          mkdir -p /var/www/tetardpg/backend
          rsync -a --delete dist/ /var/www/tetardpg/backend/dist/
          rsync -a package.json package-lock.json /var/www/tetardpg/backend/
          cd /var/www/tetardpg/backend && npm ci --omit=dev

      - name: Restart pm2
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        run: |
          su - tetardtek-brain -c 'pm2 reload tetardpg-backend --update-env'

      # ── Frontend ─────────────────────────────────────────────────────────────
      - name: Install & build frontend
        working-directory: frontend
        env:
          VITE_API_URL: https://tetardpg.tetardtek.com/api
          VITE_OAUTH_URL: https://superoauth.tetardtek.com
          VITE_OAUTH_CLIENT_ID: tetardpg
        run: |
          npm ci
          npm run build

      - name: Deploy frontend
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        run: |
          mkdir -p /var/www/tetardpg/frontend/dist
          rsync -a --delete frontend/dist/ /var/www/tetardpg/frontend/dist/

      # ── Smoke test ───────────────────────────────────────────────────────────
      - name: Smoke test API
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        run: |
          sleep 3
          curl -sf http://localhost:4000/api/health | grep -q '"ok"'
          echo "✅ API health OK"
