name: CI

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

env:
  NODE_VERSION: '18'
  YARN_VERSION: '4.12.0'

jobs:
  # Job 1: Lint (Lint backend + root esconfig)
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'yarn'
      - run: yarn install
      - run: yarn lint

  # Job 2: Backend Tests
  test-backend:
    needs: lint
    runs-on: ubuntu-latest
    env:
      DATABASE_URL: 'file:./test.db'
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'yarn'
      - run: yarn install
      - run: cd backend && yarn test:ci

  # Job 3: Frontend Tests
  test-frontend:
    needs: lint
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'yarn'
      - run: yarn install
      - run: cd frontend && yarn test:run

  # Job 4: E2E Tests (BLOQUEANTE - must pass)
  test-e2e:
    needs:
      - test-backend
      - test-frontend
    runs-on: ubuntu-latest
    env:
      DATABASE_URL: 'file:./test.db'
      IGDB_CLIENT_ID: ${{ secrets.IGDB_CLIENT_ID }}
      IGDB_CLIENT_SECRET: ${{ secrets.IGDB_CLIENT_SECRET }}
      RAWG_API_KEY: ${{ secrets.RAWG_API_KEY }}
      THEGAMESDB_API_KEY: ${{ secrets.THEGAMESDB_API_KEY }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'yarn'
      - run: yarn install
      - run: yarn test:install

      # Start backend in background
      - run: |
          cd backend && yarn dev &
          sleep 5
        shell: bash

      # Start frontend in background
      - run: |
          cd frontend && yarn dev &
          sleep 5
        shell: bash

      # Run E2E tests (timeout 5 min)
      - run: |
          timeout 300 yarn test:e2e --reporter=list || true
        shell: bash

      # Upload Playwright report on failure
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 7
