name: CI

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

env:
  NODE_VERSION: "22"

jobs:
  lint-typecheck-test:
    name: Lint · Typecheck · Test · Build
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:16-alpine
        env:
          POSTGRES_USER: tuvi
          POSTGRES_PASSWORD: tuvi_test
          POSTGRES_DB: tuvi_test
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U tuvi"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    env:
      DATABASE_URL: postgresql://tuvi:***@localhost:5432/tuvi_test
      ...n      NEXTAUTH_URL: http://localhost:3000
      NEXTAUTH_SECRET: ci_test_secret_thirty_two_chars_min_length

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: npm

      - name: Install
        run: npm ci

      - name: Prisma generate
        run: npx prisma generate

      - name: Prisma migrate (test DB)
        run: npx prisma migrate deploy

      - name: Format check
        run: npm run format:check

      - name: Lint
        run: npm run lint

      - name: Typecheck
        run: npm run typecheck

      - name: Unit tests
        run: npm run test

      - name: Build
        run: npm run build

  e2e:
    name: E2E (Playwright)
    runs-on: ubuntu-latest
    needs: lint-typecheck-test

    services:
      postgres:
        image: postgres:16-alpine
        env:
          POSTGRES_USER: tuvi
          POSTGRES_PASSWORD: tuvi_test
          POSTGRES_DB: tuvi_test
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U tuvi"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    env:
      DATABASE_URL: postgresql://tuvi:***@localhost:5432/tuvi_test
      ...n      NEXTAUTH_URL: http://localhost:3000
      NEXTAUTH_SECRET: ci_test_secret_thirty_two_chars_min_length

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: npm

      - name: Install
        run: npm ci

      - name: Prisma migrate
        run: npx prisma migrate deploy

      - name: Seed
        run: npm run db:seed

      - name: Build
        run: npm run build

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

      - name: Run E2E tests
        run: npm run test:e2e

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