name: CI

on:
  pull_request:
    types: [opened, synchronize, reopened]

permissions:
  contents: read

jobs:
  tests:
    runs-on: ubuntu-latest

    # 1) Add a Postgres service for CI
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: testdb
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U postgres"
          --health-interval 5s
          --health-timeout 5s
          --health-retries 20

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          lfs: true

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Create .env for CI
        run: |
          cat > .env <<'EOF'
          DEBUG=True
          SECRET_KEY=ci-test-secret-key-not-for-production
          ALLOWED_HOSTS=*
          CORS_ALLOWED_ORIGINS=http://localhost
          SUPERUSER_PASSWORD=testpass
          DB_NAME=testdb
          DB_USER=postgres
          DB_PASSWORD=postgres
          DB_HOST=host.docker.internal
          DB_PORT=5432
          CELERY_BROKER_URL=redis://localhost:6379/0
          CELERY_DEFAULT_QUEUE=celery
          USE_S3=False
          SECURE_SSL_REDIRECT=False
          EOF

      - name: Build test image (with dev deps)
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          load: true
          tags: {{ project_name }}:{% raw %}${{ github.sha }}{% endraw %}

          build-args: |
            PDM_GROUPS=--dev

          cache-from: type=gha
          cache-to: type=gha,mode=max

      # 2) Wait for DB to be up (from the host)
      - name: Wait for Postgres
        run: |
          for i in {1..60}; do
            if docker run --rm --network host postgres:16 pg_isready -h 127.0.0.1 -p 5432 -U postgres; then
              echo "Postgres is ready"; exit 0
            fi
            echo "Waiting for Postgres... ($i/60)"; sleep 2
          done
          echo "Postgres failed to start in time"; exit 1

      - name: Lint inside container
        run: |
          docker run --rm \
            --add-host=host.docker.internal:host-gateway \
            --entrypoint bash \
            --env-file .env \
            -e PYTHONPATH=/app \
            -e DJANGO_SETTINGS_MODULE=main.settings \
            {{ project_name }}:{% raw %}${{ github.sha }}{% endraw %} \
            -lc 'pdm run lint-check'

      - name: Run tests inside container
        run: |
          docker run --rm \
            --add-host=host.docker.internal:host-gateway \
            --entrypoint bash \
            --env-file .env \
            -e PYTHONPATH=/app \
            -e DJANGO_SETTINGS_MODULE=main.settings \
            {{ project_name }}:{% raw %}${{ github.sha }}{% endraw %} \
            -lc 'pdm run python manage.py migrate --noinput && pdm run pytest -q'
