name: Cypress Smoke Tests

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

env:
  NEXT_PUBLIC_ACTIVE_THEME: ${{ vars.ACTIVE_THEME || 'default' }}

jobs:
  smoke-tests:
    name: Smoke Tests
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: 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 Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

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

      - name: Get pnpm store directory
        shell: bash
        run: |
          echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV

      - name: Setup pnpm cache
        uses: actions/cache@v4
        with:
          path: ${{ env.STORE_PATH }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-

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

      - name: Setup database
        env:
          DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test
        run: pnpm db:migrate

      - name: Build application
        run: pnpm build

      - name: Run Smoke Tests
        uses: cypress-io/github-action@v6
        with:
          start: pnpm start
          wait-on: 'http://localhost:5173'
          wait-on-timeout: 120
          config-file: contents/themes/${{ env.NEXT_PUBLIC_ACTIVE_THEME }}/tests/cypress.config.ts
          env: grepTags=@smoke
        env:
          DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test

      - name: Upload screenshots on failure
        uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: cypress-screenshots
          path: contents/themes/${{ env.NEXT_PUBLIC_ACTIVE_THEME }}/tests/cypress/screenshots
          retention-days: 7

      - name: Upload videos
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: cypress-videos
          path: contents/themes/${{ env.NEXT_PUBLIC_ACTIVE_THEME }}/tests/cypress/videos
          retention-days: 3
