name: Tests

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

jobs:
  go-tests:
    name: Go Tests
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:16-alpine
        env:
          POSTGRES_USER: breakpilot
          POSTGRES_PASSWORD: breakpilot123
          POSTGRES_DB: breakpilot_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: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.21'
          cache: true
          cache-dependency-path: consent-service/go.sum

      - name: Install Dependencies
        working-directory: ./consent-service
        run: go mod download

      - name: Run Tests
        working-directory: ./consent-service
        env:
          DATABASE_URL: postgres://breakpilot:breakpilot123@localhost:5432/breakpilot_test?sslmode=disable
          JWT_SECRET: test-secret-key-for-ci
          JWT_REFRESH_SECRET: test-refresh-secret-for-ci
        run: |
          go test -v -race -coverprofile=coverage.out ./...
          go tool cover -func=coverage.out

      - name: Check Coverage Threshold
        working-directory: ./consent-service
        run: |
          COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//')
          echo "Total Coverage: $COVERAGE%"
          if (( $(echo "$COVERAGE < 70.0" | bc -l) )); then
            echo "Coverage $COVERAGE% is below threshold 70%"
            exit 1
          fi

      - name: Upload Coverage to Codecov
        uses: codecov/codecov-action@v3
        with:
          files: ./consent-service/coverage.out
          flags: go
          name: go-coverage

  python-tests:
    name: Python Tests
    runs-on: ubuntu-latest

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

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.10'
          cache: 'pip'
          cache-dependency-path: backend/requirements.txt

      - name: Install Dependencies
        working-directory: ./backend
        run: |
          pip install --upgrade pip
          pip install -r requirements.txt
          pip install pytest pytest-cov pytest-asyncio

      - name: Run Tests
        working-directory: ./backend
        env:
          CONSENT_SERVICE_URL: http://localhost:8081
          JWT_SECRET: test-secret-key-for-ci
        run: |
          pytest -v --cov=. --cov-report=xml --cov-report=term

      - name: Check Coverage Threshold
        working-directory: ./backend
        run: |
          COVERAGE=$(python -c "import xml.etree.ElementTree as ET; tree = ET.parse('coverage.xml'); print(tree.getroot().attrib['line-rate'])")
          COVERAGE_PCT=$(echo "$COVERAGE * 100" | bc)
          echo "Total Coverage: ${COVERAGE_PCT}%"
          if (( $(echo "$COVERAGE_PCT < 60.0" | bc -l) )); then
            echo "Coverage ${COVERAGE_PCT}% is below threshold 60%"
            exit 1
          fi

      - name: Upload Coverage to Codecov
        uses: codecov/codecov-action@v3
        with:
          files: ./backend/coverage.xml
          flags: python
          name: python-coverage

  integration-tests:
    name: Integration Tests
    runs-on: ubuntu-latest

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

      - name: Setup Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Start Services
        run: |
          docker-compose up -d
          docker-compose ps

      - name: Wait for Postgres
        run: |
          timeout 60 bash -c 'until docker-compose exec -T postgres pg_isready -U breakpilot; do sleep 2; done'

      - name: Wait for Consent Service
        run: |
          timeout 60 bash -c 'until curl -f http://localhost:8081/health; do sleep 2; done'

      - name: Wait for Backend
        run: |
          timeout 60 bash -c 'until curl -f http://localhost:8000/health; do sleep 2; done'

      - name: Wait for Mailpit
        run: |
          timeout 60 bash -c 'until curl -f http://localhost:8025/api/v1/info; do sleep 2; done'

      - name: Run Integration Tests
        run: |
          chmod +x ./scripts/integration-tests.sh
          ./scripts/integration-tests.sh

      - name: Show Service Logs on Failure
        if: failure()
        run: |
          echo "=== Consent Service Logs ==="
          docker-compose logs consent-service
          echo "=== Backend Logs ==="
          docker-compose logs backend
          echo "=== Postgres Logs ==="
          docker-compose logs postgres

      - name: Cleanup
        if: always()
        run: docker-compose down -v

  lint-go:
    name: Go Lint
    runs-on: ubuntu-latest

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

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.21'

      - name: Run golangci-lint
        uses: golangci/golangci-lint-action@v3
        with:
          version: latest
          working-directory: consent-service
          args: --timeout=5m

  lint-python:
    name: Python Lint
    runs-on: ubuntu-latest

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

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.10'

      - name: Install Dependencies
        run: |
          pip install flake8 black mypy

      - name: Run Black
        working-directory: ./backend
        run: black --check .

      - name: Run Flake8
        working-directory: ./backend
        run: flake8 . --max-line-length=120 --exclude=venv

  security-scan:
    name: Security Scan
    runs-on: ubuntu-latest

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

      - name: Run Trivy Security Scan
        uses: aquasecurity/trivy-action@master
        with:
          scan-type: 'fs'
          scan-ref: '.'
          format: 'sarif'
          output: 'trivy-results.sarif'

      - name: Upload Trivy Results to GitHub Security
        uses: github/codeql-action/upload-sarif@v2
        if: always()
        with:
          sarif_file: 'trivy-results.sarif'

  all-checks:
    name: All Checks Passed
    runs-on: ubuntu-latest
    needs: [go-tests, python-tests, integration-tests, lint-go, lint-python, security-scan]

    steps:
      - name: All Tests Passed
        run: echo "All tests and checks passed successfully!"
