name: Integration Tests

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

env:
  CARGO_TERM_COLOR: always
  DATABASE_URL: postgresql://postgres:postgres@localhost:5432/readur_test

jobs:
  integration-tests:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:17
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: readur_test
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

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

      - name: Remove local env files to prevent conflicts
        run: |
          # Remove or rename env files so they don't override CI environment variables
          [ -f .env ] && mv .env .env.backup || true
          [ -f .env.test ] && mv .env.test .env.test.backup || true
          echo "Removed local env files to ensure CI env vars take precedence"

      - 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

      - 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-release-${{ hashFiles('**/Cargo.lock') }}-${{ hashFiles('**/*.rs') }}
          restore-keys: |
            ${{ runner.os }}-cargo-target-release-${{ hashFiles('**/Cargo.lock') }}-
            ${{ runner.os }}-cargo-target-release-

      - name: Build readur binary
        run: cargo build --release

      - name: Start readur server
        run: |
          echo "Starting server with DATABASE_URL: $DATABASE_URL"
          ./target/release/readur > server.log 2>&1 &
          echo $! > readur.pid
          sleep 2
          echo "Server started with PID: $(cat readur.pid)"
        env:
          DATABASE_URL: ${{ env.DATABASE_URL }}
          JWT_SECRET: test-secret-key
          SERVER_ADDRESS: 0.0.0.0:8000
          UPLOAD_PATH: ./uploads
          WATCH_FOLDER: ./watch
          DEBUG: 1

      - name: Wait for server to be ready
        run: |
          for i in {1..30}; do
            if curl -f http://localhost:8000/api/health > /dev/null 2>&1; then
              echo "Readur server is ready"
              break
            fi
            echo "Waiting for readur server... ($i/30)"
            sleep 2
          done

          # Verify the server is actually running
          if ! curl -f http://localhost:8000/api/health > /dev/null 2>&1; then
            echo "ERROR: Server failed to start properly!"
            if [ -f readur.pid ]; then
              echo "Server PID: $(cat readur.pid)"
              ps aux | grep $(cat readur.pid) || echo "Process not found"
            fi
            exit 1
          fi

      - name: Wait for PostgreSQL to be ready
        run: |
          until pg_isready -h localhost -p 5432 -U postgres; do
            echo "Waiting for PostgreSQL..."
            sleep 1
          done
          echo "PostgreSQL is ready!"

      - name: Verify database connection
        run: |
          echo "Testing database connection..."
          PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d readur_test -c "SELECT version();"
          echo "Database connection successful!"

      - name: Run integration tests
        run: |
          echo "Running tests with DATABASE_URL: $DATABASE_URL"
          echo "Environment check:"
          env | grep -E "(DATABASE_URL|JWT_SECRET|API_URL)" | sort
          cargo test --test '*' --features test-utils --no-fail-fast -- --test-threads=1
        env:
          DATABASE_URL: ${{ env.DATABASE_URL }}
          TEST_DATABASE_URL: ${{ env.DATABASE_URL }}
          API_URL: http://localhost:8000
          JWT_SECRET: test-secret-key
          SERVER_ADDRESS: 0.0.0.0:8000
          UPLOAD_PATH: ./uploads
          WATCH_FOLDER: ./watch
          RUST_LOG: debug
          RUST_BACKTRACE: 1
          DEBUG: 1

      - name: Print server logs on failure
        if: failure()
        run: |
          echo "=== Server logs ==="
          cat server.log || echo "No server logs found"
          echo "=== End of server logs ==="

      - name: Stop readur server
        if: always()
        run: |
          if [ -f readur.pid ]; then
            kill $(cat readur.pid) || true
            rm readur.pid
          fi
