name: CI

on:
  push:
  pull_request:

jobs:
  # ─── Unit & Browser Component Tests ──────────────────────────────────────────
  # Runs inside the official Playwright Docker image — Chromium and all system
  # deps are pre-installed, so no install or cache step is needed for the browser.
  unit-tests:
    name: Unit & Component Tests
    runs-on: ubuntu-latest
    container:
      image: mcr.microsoft.com/playwright:v1.58.2-noble
    steps:
      - uses: actions/checkout@v4

      - name: Cache node_modules
        id: node-modules-cache
        uses: actions/cache@v4
        with:
          path: frontend/node_modules
          key: node-modules-${{ hashFiles('frontend/package-lock.json') }}

      - name: Install dependencies
        if: steps.node-modules-cache.outputs.cache-hit != 'true'
        run: npm ci
        working-directory: frontend

      - name: Compile Paraglide i18n
        run: npx @inlang/paraglide-js compile --project ./project.inlang --outdir ./src/lib/paraglide
        working-directory: frontend

      - name: Lint
        run: npm run lint
        working-directory: frontend

      - name: Run unit and component tests
        run: npm test
        working-directory: frontend

      - name: Upload screenshots
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: unit-test-screenshots
          path: frontend/test-results/screenshots/

  # ─── OCR Service Unit Tests ───────────────────────────────────────────────────
  # Only spell_check.py, test_confidence.py, test_sender_registry.py — no ML stack required.
  ocr-tests:
    name: OCR Service Tests
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install test dependencies
        run: pip install "pyspellchecker==0.9.0" pytest pytest-asyncio
        working-directory: ocr-service

      - name: Run OCR unit tests (no ML stack required)
        run: python -m pytest test_spell_check.py test_confidence.py test_sender_registry.py -v
        working-directory: ocr-service

  # ─── Backend Unit & Slice Tests ───────────────────────────────────────────────
  # Pure Mockito + WebMvcTest — no DB or S3 needed.
  backend-unit-tests:
    name: Backend Unit Tests
    runs-on: ubuntu-latest
    env:
      DOCKER_API_VERSION: "1.43"  # NAS runner runs Docker 24.x (max API 1.43); Testcontainers 2.x defaults to 1.44
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: temurin

      - name: Cache Maven repository
        uses: actions/cache@v4
        with:
          path: ~/.m2/repository
          key: maven-${{ hashFiles('backend/pom.xml') }}
          restore-keys: maven-

      - name: Run backend tests
        run: |
          chmod +x mvnw
          ./mvnw clean test
        working-directory: backend