name: Cypress E2E Tests

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

jobs:
  cypress-run:
    runs-on: ubuntu-latest
    
    strategy:
      matrix:
        node-version: [18.x, 20.x]
    
    steps:
    - name: Checkout
      uses: actions/checkout@v4
    
    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
    
    - name: Install dependencies
      run: npm ci
    
    - name: Build application
      run: npm run build
    
    - name: Start application
      run: npm run preview &
      
    - name: Wait for application to start
      run: npx wait-on http://localhost:4173 --timeout 60000
    
    - name: Run Cypress tests
      uses: cypress-io/github-action@v6
      with:
        start: npm run preview
        wait-on: 'http://localhost:4173'
        wait-on-timeout: 120
        browser: chrome
        record: true
        parallel: true
      env:
        CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    
    - name: Upload screenshots
      uses: actions/upload-artifact@v4
      if: failure()
      with:
        name: cypress-screenshots-${{ matrix.node-version }}
        path: cypress/screenshots
    
    - name: Upload videos
      uses: actions/upload-artifact@v4
      if: always()
      with:
        name: cypress-videos-${{ matrix.node-version }}
        path: cypress/videos
    
    - name: Upload test results
      uses: actions/upload-artifact@v4
      if: always()
      with:
        name: cypress-results-${{ matrix.node-version }}
        path: cypress/reports

  lighthouse:
    runs-on: ubuntu-latest
    needs: cypress-run
    
    steps:
    - name: Checkout
      uses: actions/checkout@v4
    
    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: '20.x'
        cache: 'npm'
    
    - name: Install dependencies
      run: npm ci
    
    - name: Build and start application
      run: |
        npm run build
        npm run preview &
        
    - name: Wait for application
      run: npx wait-on http://localhost:4173 --timeout 60000
    
    - name: Run Lighthouse CI
      run: |
        npm install -g @lhci/cli@0.12.x
        lhci autorun
      env:
        LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }}