name: Unit Tests

on:
  push:
    branches:
      - master
      - main
  pull_request:
    branches:
      - master
      - main

env:
  CARGO_TERM_COLOR: always

jobs:
  rust-unit-tests:
    runs-on: ubuntu-latest

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

      - name: Install system dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y \
            tesseract-ocr \
            tesseract-ocr-eng \
            libtesseract-dev \
            libleptonica-dev \
            pkg-config \
            libclang-dev \
            ocrmypdf \
            clang

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - name: Cache cargo registry
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
          key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-registry-

      - name: Cache target directory
        uses: actions/cache@v4
        with:
          path: target
          key: ${{ runner.os }}-cargo-target-${{ hashFiles('**/Cargo.lock') }}-${{ hashFiles('**/*.rs') }}
          restore-keys: |
            ${{ runner.os }}-cargo-target-${{ hashFiles('**/Cargo.lock') }}-
            ${{ runner.os }}-cargo-target-

      - name: Run Rust unit tests
        run: |
          cargo test --lib --no-fail-fast
          cargo test --tests unit_tests --no-fail-fast
        env:
          RUST_BACKTRACE: 1

  frontend-unit-tests:
    runs-on: ubuntu-latest

    defaults:
      run:
        working-directory: ./frontend

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "22"
          cache: "npm"
          cache-dependency-path: frontend/package-lock.json

      - name: Install dependencies
        run: npm install

      - name: Run type checking
        run: npm run type-check

      - name: Run unit tests
        run: npm test -- --run
