name: Test Coverage

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

jobs:
  test-coverage:
    name: Run Tests with Coverage
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.23'
          check-latest: true

      - name: Run tests with coverage
        run: |
          go test -coverprofile=coverage.out ./...

      - name: Generate coverage report
        run: |
          go tool cover -html=coverage.out -o coverage.html

      - name: Display coverage summary
        run: |
          echo "## 📊 Test Coverage Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
          go tool cover -func=coverage.out | tail -1 >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY

      - name: Upload coverage report
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: coverage.html
          retention-days: 30

      - name: Comment PR with coverage
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            const { execSync } = require('child_process');
            const coverage = execSync('go tool cover -func=coverage.out | tail -1', { encoding: 'utf-8' });
            const body = `## 📊 Test Coverage Report
            
            \`\`\`
            ${coverage}
            \`\`\`
            
            Coverage report available in artifacts.
            `;
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: body
            });
