name: CI

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

jobs:
  # =============================================
  # Backend CI
  # =============================================
  backend:
    name: Backend (Go)
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ./thpark_server

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

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

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version-file: ./thpark_server/go.mod
          cache-dependency-path: ./thpark_server/go.sum

      - name: Install dependencies
        run: go mod download

      - name: Run tests
        env:
          APP_ENV: test
          THPARK_DATABASE_PASSWORD: postgres
          THPARK_SERVER_JWT_SECRET: test-jwt-secret-do-not-use-in-production
        run: go test ./... -v -race -coverprofile=coverage.out

      - name: Build binary
        run: go build -o thpark-server main.go

      - name: Upload coverage
        uses: actions/upload-artifact@v4
        with:
          name: backend-coverage
          path: ./thpark_server/coverage.out
          retention-days: 7

  # =============================================
  # Frontend CI
  # =============================================
  frontend:
    name: Frontend (React + Vite)
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ./thpark_admin

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: 'pnpm'
          cache-dependency-path: ./thpark_admin/pnpm-lock.yaml

      - name: Install pnpm
        uses: pnpm/action-setup@v3
        with:
          version: 9
          run_install: false

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

      - name: Run linter
        run: pnpm lint

      - name: Run tests
        run: pnpm test:run

      - name: Build
        run: pnpm build
