name: Deploy Backend to Staging

on:
  push:
    branches: [main]

jobs:
  deploy:
    name: Deploy backend to staging
    runs-on: self-hosted
    steps:
      - name: Pull latest code
        run: |
          cd /opt/encoach/encoach_backend_new_v2
          git fetch origin
          git reset --hard origin/main
          echo "Deployed: $(git log -1 --oneline)"

      - name: Build Odoo image
        run: |
          cd /opt/encoach/encoach_backend_new_v2
          # odoo.conf is not in the repo; copy from the persistent override for the build context
          cp /opt/encoach/overrides/odoo.conf ./odoo.conf
          docker compose \
            -f docker-compose.yml \
            -f /opt/encoach/overrides/encoach.override.yml \
            build odoo
          rm -f ./odoo.conf

      - name: Run DB migrations
        run: |
          # Dynamically fetch the list of installed encoach_* modules from the DB
          MODULES=$(docker exec encoach-v4-db psql -U odoo -d encoach_v2 -tAc \
            "SELECT string_agg(name, ,) FROM ir_module_module WHERE state=installed AND name LIKE encoach%;")
          echo "Upgrading modules: $MODULES"

          docker run --rm \
            --network encoach_backend_new_v2_default \
            -v /opt/encoach/overrides/odoo.conf:/etc/odoo/odoo.conf:ro \
            -v /opt/encoach/encoach_backend_new_v2:/mnt/extra-addons:ro \
            -v /opt/encoach/encoach_backend_new_v2/openeducat_erp-19.0/openeducat_erp-19.0:/mnt/extra-addons/openeducat_erp-19.0:ro \
            -v encoach_backend_new_v2_odoo-web-data:/var/lib/odoo \
            encoach-backend:latest \
            odoo -u "$MODULES" --stop-after-init 2>&1 | tail -20

      - name: Restart Odoo
        run: |
          cd /opt/encoach/encoach_backend_new_v2
          docker compose \
            -f docker-compose.yml \
            -f /opt/encoach/overrides/encoach.override.yml \
            up -d --no-deps odoo

      - name: Smoke test
        run: |
          echo "Polling Odoo /api/health (max 180s)..."
          STATUS="000"
          for i in $(seq 1 18); do
            STATUS=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 http://localhost:8069/api/health 2>/dev/null || echo "000")
            [ "$STATUS" = "200" ] && echo "Odoo healthy after $((i*10))s" && break
            echo "  attempt $i: $STATUS — waiting 10s..."
            sleep 10
          done
          [ "$STATUS" != "200" ] && echo "ERROR: Odoo still $STATUS after 180s" && exit 1
          FE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 http://localhost:3000/ 2>/dev/null || echo "000")
          [ "$FE" != "200" ] && echo "ERROR: Frontend $FE" && exit 1
          echo "All OK — Odoo=200 Frontend=$FE"
