name: CI Pipeline

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

jobs:
  # ── 后端 ──────────────────────────────────────────────
  backend-lint-test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_USER: test
          POSTGRES_PASSWORD: test
          POSTGRES_DB: geo_test
        ports: ['5432:5432']
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
      redis:
        image: redis:7
        ports: ['6379:6379']
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'

      - name: Install dependencies
        run: |
          cd backend
          pip install -r requirements.txt
          pip install ruff pytest-cov

      - name: Lint (ruff)
        run: cd backend && ruff check app/

      - name: Type check (optional)
        run: cd backend && ruff check app/ --select=E,W
        continue-on-error: true

      - name: Run tests
        env:
          DATABASE_URL: postgresql+asyncpg://test:test@localhost:5432/geo_test
          REDIS_URL: redis://localhost:6379/0
          JWT_SECRET: test-secret-key-minimum-32-characters-long
          ENVIRONMENT: test
        run: |
          cd backend
          pytest tests/ -v --tb=short

  # ── 前端 ──────────────────────────────────────────────
  frontend-lint-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: frontend/package-lock.json

      - name: Install dependencies
        run: cd frontend && npm ci

      - name: Lint (ESLint)
        run: cd frontend && npm run lint

      - name: Type check
        run: cd frontend && npx tsc --noEmit

      - name: Unit tests
        run: cd frontend && npm run test:ci

  # ── Docker build 验证 ──────────────────────────────────
  docker-build:
    runs-on: ubuntu-latest
    needs: [backend-lint-test, frontend-lint-test]
    steps:
      - uses: actions/checkout@v4

      - name: Build backend image
        run: docker build -t geo-backend:test ./backend

      - name: Build frontend image
        run: docker build -t geo-frontend:test ./frontend
