name: CI

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

concurrency:
  group: ci-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

env:
  NODE_VERSION: '20'

jobs:
  lint-types-build:
    name: Lint, types, build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: npm
      - run: npm ci
      - name: Generate Prisma client
        run: npx prisma generate
      - run: npm run lint
      - name: Type check
        run: npx tsc --noEmit
      - name: Build
        run: npm run build
        env:
          # Build-time env. Real values come from Cloud Run / Vercel — set non-empty defaults
          # here so the build doesn't crash on missing required vars.
          DATABASE_URL: postgresql://ci:ci@localhost:5432/ci
          NEXTAUTH_SECRET: ci-secret-only-for-build
          NEXTAUTH_URL: http://localhost:3000

  # NOTE: echos-ocr has no test runner configured yet (no vitest / jest /
  # playwright in package.json). Re-enable this job once a test runner is
  # adopted and a `test:run` script exists in package.json. Until then,
  # this block stays commented so CI doesn't fail on a missing script.
  #
  # test:
  #   name: Unit + integration tests
  #   runs-on: ubuntu-latest
  #   services:
  #     postgres:
  #       image: postgres:16
  #       env:
  #         POSTGRES_USER: ci
  #         POSTGRES_PASSWORD: ci
  #         POSTGRES_DB: ci
  #       ports: ['5432:5432']
  #       options: >-
  #         --health-cmd "pg_isready -U ci"
  #         --health-interval 5s
  #         --health-timeout 5s
  #         --health-retries 10
  #   steps:
  #     - uses: actions/checkout@v4
  #     - uses: actions/setup-node@v4
  #       with:
  #         node-version: ${{ env.NODE_VERSION }}
  #         cache: npm
  #     - run: npm ci
  #     - run: npx prisma generate
  #     - name: Run migrations
  #       run: npx prisma migrate deploy
  #       env:
  #         DATABASE_URL: postgresql://ci:ci@localhost:5432/ci
  #     - run: npm run test:run
  #       env:
  #         DATABASE_URL: postgresql://ci:ci@localhost:5432/ci
  #         NEXTAUTH_SECRET: ci-secret-only-for-tests
  #         NEXTAUTH_URL: http://localhost:3000

  schema-map-fresh:
    name: Schema map up to date
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: npm
      - run: npm ci
      - name: Regenerate schema map
        run: npm run schema:map
      - name: Verify no drift
        run: |
          if ! git diff --quiet docs/SCHEMA_MAP.md; then
            echo "::error::docs/SCHEMA_MAP.md is out of date. Run 'npm run schema:map' and commit."
            git diff docs/SCHEMA_MAP.md
            exit 1
          fi
