name: Tests

on:
  push:
    branches: [main, develop, dev]
  pull_request:
    branches: [main, develop, dev]

jobs:
  test:
    name: Unit & Integration Tests
    runs-on: ubuntu-latest
    timeout-minutes: 10

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

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

      - name: Generate coverage report
        run: npm run test:coverage
        continue-on-error: true

      - name: Upload coverage report
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: coverage-report
          path: coverage/
          retention-days: 30

      - name: Comment PR with coverage
        if: always() && github.event_name == 'pull_request'
        uses: actions/github-script@v7
        continue-on-error: true
        with:
          script: |
            const fs = require('fs');
            if (fs.existsSync('coverage/coverage-summary.json')) {
              const coverage = JSON.parse(fs.readFileSync('coverage/coverage-summary.json', 'utf8'));
              const total = coverage.total;

              const comment = `## Test Coverage Report

              | Metric | Coverage |
              |--------|----------|
              | Lines | ${total.lines.pct}% |
              | Statements | ${total.statements.pct}% |
              | Functions | ${total.functions.pct}% |
              | Branches | ${total.branches.pct}% |

              [View detailed coverage report in artifacts](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})
              `;

              github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body: comment
              });
            }

      - name: Test Summary
        if: always()
        run: |
          echo "## Test Results" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "✅ All tests completed" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "See artifacts for coverage reports." >> $GITHUB_STEP_SUMMARY
