name: Tests

on:
  push:
    branches: [master, main, daybook]
  pull_request:
    branches: [master, main]

jobs:
  test:
    name: PHPUnit Tests
    runs-on: ubuntu-latest
    timeout-minutes: 10

    services:
      mysql:
        image: mysql:8.0
        env:
          MYSQL_ROOT_PASSWORD: root
          MYSQL_DATABASE: kiosk_test
        ports:
          - 3306:3306
        options: >-
          --health-cmd="mysqladmin ping"
          --health-interval=10s
          --health-timeout=5s
          --health-retries=5

      redis:
        image: redis:7
        ports:
          - 6379:6379
        options: >-
          --health-cmd="redis-cli ping"
          --health-interval=10s
          --health-timeout=5s
          --health-retries=5

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

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
          extensions: mbstring, pdo_mysql, redis, xdebug
          coverage: xdebug
          tools: composer:v2

      - name: Get Composer cache directory
        id: composer-cache
        run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT

      - name: Cache Composer dependencies
        uses: actions/cache@v4
        with:
          path: ${{ steps.composer-cache.outputs.dir }}
          key: ${{ runner.os }}-composer-${{ hashFiles('userfrosting/composer.lock') }}
          restore-keys: |
            ${{ runner.os }}-composer-

      - name: Install dependencies
        working-directory: userfrosting
        run: composer install --prefer-dist --no-progress

      - name: Create test environment file
        working-directory: userfrosting
        run: |
          cat > .env.testing << 'EOF'
          DB_HOST=127.0.0.1
          DB_PORT=3306
          DB_USER=root
          DB_PASSWORD=root
          DB_NAME=kiosk_test
          REDIS_HOST=127.0.0.1
          REDIS_PORT=6379
          APP_ENV=testing
          EOF

      - name: Set up test database
        run: |
          mysql -h 127.0.0.1 -u root -proot -e "CREATE DATABASE IF NOT EXISTS kiosk_test;"
          mysql -h 127.0.0.1 -u root -proot -e "CREATE DATABASE IF NOT EXISTS kiosk_users;"
          mysql -h 127.0.0.1 -u root -proot -e "CREATE DATABASE IF NOT EXISTS kiosk_buykiosk;"

      - name: Run tests
        run: ./test.sh

      - name: Run tests with coverage
        if: github.event_name == 'pull_request'
        run: |
          cd userfrosting
          XDEBUG_MODE=coverage php vendor/bin/phpunit --coverage-clover coverage.xml --coverage-html coverage-html
        continue-on-error: false

      - name: Upload coverage report
        if: github.event_name == 'pull_request'
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: userfrosting/coverage-html
          retention-days: 7

      - name: Upload coverage to Codecov
        if: github.event_name == 'pull_request'
        uses: codecov/codecov-action@v4
        with:
          files: userfrosting/coverage.xml
          fail_ci_if_error: false
          verbose: true
        continue-on-error: true

      - name: Check coverage threshold
        if: github.event_name == 'pull_request'
        run: |
          cd userfrosting
          # Parse coverage from clover.xml and check threshold
          # Target: 80% for changed files (informational for now)
          if [ -f coverage.xml ]; then
            COVERAGE=$(php -r "
              \$xml = simplexml_load_file('coverage.xml');
              \$metrics = \$xml->project->metrics;
              \$elements = (int)\$metrics['elements'];
              \$covered = (int)\$metrics['coveredelements'];
              if (\$elements > 0) {
                echo round((\$covered / \$elements) * 100, 2);
              } else {
                echo '0';
              }
            ")
            echo "Overall coverage: ${COVERAGE}%"
            if (( $(echo "$COVERAGE < 80" | bc -l) )); then
              echo "::warning::Coverage is below 80% threshold"
            fi
          fi

      - name: Generate coverage badge
        if: github.event_name == 'push' && github.ref == 'refs/heads/master'
        run: |
          cd userfrosting
          if [ -f coverage.xml ]; then
            COVERAGE=$(php -r "
              \$xml = simplexml_load_file('coverage.xml');
              \$metrics = \$xml->project->metrics;
              \$elements = (int)\$metrics['elements'];
              \$covered = (int)\$metrics['coveredelements'];
              if (\$elements > 0) {
                echo round((\$covered / \$elements) * 100, 0);
              } else {
                echo '0';
              }
            ")
            # Determine badge color based on coverage
            if (( COVERAGE >= 90 )); then
              COLOR="brightgreen"
            elif (( COVERAGE >= 80 )); then
              COLOR="green"
            elif (( COVERAGE >= 70 )); then
              COLOR="yellow"
            else
              COLOR="red"
            fi
            echo "Badge: coverage-${COVERAGE}%-${COLOR}"
            # Badge can be generated via shields.io: https://img.shields.io/badge/coverage-${COVERAGE}%25-${COLOR}
          fi

  lint:
    name: PHP Syntax Check
    runs-on: ubuntu-latest
    timeout-minutes: 5

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

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
          tools: php-parallel-lint

      - name: Check PHP syntax
        run: |
          find userfrosting/src -name "*.php" -print0 | xargs -0 -n1 php -l > /dev/null

  # Deployment job - only runs on merge to master after tests pass
  deploy:
    name: Deploy to Production
    runs-on: ubuntu-latest
    needs: [test, lint]
    if: github.event_name == 'push' && github.ref == 'refs/heads/master'

    steps:
      - name: Trigger Envoyer deployment
        run: |
          echo "Triggering Envoyer deployment..."
          # Note: In production, use secrets for the webhook URL
          # curl -s '${{ secrets.ENVOYER_WEBHOOK_URL }}'
          echo "Deployment webhook would be triggered here"
          echo "Configure ENVOYER_WEBHOOK_URL secret to enable automatic deployment"

      - name: Deployment notification
        run: |
          echo "Deployment triggered successfully!"
          echo "Monitor deployment at: https://envoyer.io"
