name: E2E Tests

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

jobs:
  e2e-tests:
    runs-on: ubuntu-latest
    timeout-minutes: 30

    services:
      mysql:
        image: mysql:8.0.36
        env:
          MYSQL_DATABASE: test_d8dai
          MYSQL_ROOT_PASSWORD: test_password
          MYSQL_USER: test_user
          MYSQL_PASSWORD: test_password
        options: >-
          --health-cmd="mysqladmin ping"
          --health-interval=10s
          --health-timeout=5s
          --health-retries=3
        ports:
          - 3306:3306

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

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

    - name: Install pnpm
      uses: pnpm/action-setup@v2
      with:
        version: 8

    - name: Install dependencies
      run: pnpm install --frozen-lockfile

    - name: Install Playwright browsers
      run: npx playwright install --with-deps chromium

    - name: Setup test environment
      run: |
        cp .env.example .env.test
        echo "DATABASE_URL=mysql://root:test_password@localhost:3306/test_d8dai" >> .env.test
        echo "NODE_ENV=test" >> .env.test

    - name: Run database migrations
      run: |
        export NODE_ENV=test
        pnpm db:migrate

    - name: Run E2E tests
      run: |
        export NODE_ENV=test
        pnpm test:e2e --project=chromium
      env:
        E2E_BASE_URL: http://localhost:8080

    - name: Upload test results
      if: always()
      uses: actions/upload-artifact@v4
      with:
        name: playwright-report
        path: tests/e2e/playwright-report/
        retention-days: 7

    - name: Upload test results (JUnit)
      if: always()
      uses: actions/upload-artifact@v4
      with:
        name: test-results
        path: test-results/
        retention-days: 7

    - name: Generate test summary
      if: always()
      uses: test-summary/action@v2
      with:
        paths: test-results/junit.xml

    - name: Analyze test results
      if: always()
      run: pnpm test:analyze

    - name: Notify on failure
      if: failure()
      uses: 8398a7/action-slack@v3
      with:
        status: ${{ job.status }}
        channel: '#ci-notifications'
        webhook_url: ${{ secrets.SLACK_WEBHOOK }}
      env:
        SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}