name: Bird Survey CI

on:
  push:
    branches:
      - main
      - develop
  pull_request:
    branches:
      - main

env:
  NODE_VERSION: "20"
  POSTGRES_DB: bird_survey_test
  POSTGRES_USER: survey_user
  POSTGRES_PASSWORD: survey_password
  DATABASE_URL: postgres://survey_user:survey_password@localhost:5432/bird_survey_test

jobs:
  test:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgis/postgis:16-3.4
        ports:
          - 5432:5432
        env:
          POSTGRES_DB: bird_survey_test
          POSTGRES_USER: survey_user
          POSTGRES_PASSWORD: survey_password
        options: >-
          --health-cmd "pg_isready -U survey_user -d bird_survey_test"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Run database migrations
        run: npm run db:migrate

      - name: Validate species checklist
        run: npm run validate:taxonomy
        env:
          TAXONOMY_SOURCE: ebird
          REGION_CODE: US-CA

      - name: Lint source
        run: npm run lint

      - name: Run unit tests
        run: npm test

      - name: Run survey import smoke test
        run: npm run test:imports
        env:
          SAMPLE_OBSERVATION_FILE: fixtures/surveys/spring-migration-observations.csv

      - name: Build application
        run: npm run build

  deploy-preview:
    runs-on: ubuntu-latest
    needs: test
    if: github.event_name == 'pull_request'

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Deploy preview environment
        run: npm run deploy:preview
        env:
          SURVEY_PROJECT: lakeside-bird-count
          MAP_TILE_PROVIDER: openstreetmap
          OBSERVATION_UPLOAD_LIMIT_MB: "25"
          PREVIEW_TOKEN: ${{ secrets.PREVIEW_TOKEN }}