name: Test

on:
  push:
    branches:
      - main
      - develop
  pull_request:
    branches:
      - main

jobs:
  backend-test:
    runs-on: ubuntu-latest
    
    services:
      postgres:
        image: postgres:15-alpine
        env:
          POSTGRES_DB: ca_grow_ops_test
          POSTGRES_USER: test_user
          POSTGRES_PASSWORD: test_password
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432
      
      redis:
        image: redis:7-alpine
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 6379:6379
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: backend/package-lock.json
      
      - name: Install backend dependencies
        working-directory: ./backend
        run: npm ci
      
      - name: Generate Prisma Client
        working-directory: ./backend
        run: npx prisma generate
        env:
          DATABASE_URL: postgresql://test_user:test_password@localhost:5432/ca_grow_ops_test
      
      - name: Run database migrations
        working-directory: ./backend
        run: npx prisma migrate deploy
        env:
          DATABASE_URL: postgresql://test_user:test_password@localhost:5432/ca_grow_ops_test
      
      - name: Run backend tests
        working-directory: ./backend
        run: npm test
        env:
          DATABASE_URL: postgresql://test_user:test_password@localhost:5432/ca_grow_ops_test
          REDIS_URL: redis://localhost:6379
          JWT_SECRET: test_secret_key
          NODE_ENV: test
      
      - name: Run backend linter
        working-directory: ./backend
        run: npm run lint

  frontend-test:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: frontend/package-lock.json
      
      - name: Install frontend dependencies
        working-directory: ./frontend
        run: npm ci
      
      - name: Run frontend tests
        working-directory: ./frontend
        run: npm test -- --run
      
      - name: Run frontend linter
        working-directory: ./frontend
        run: npm run lint || true
      
      - name: Build frontend
        working-directory: ./frontend
        run: npm run build
        env:
          VITE_API_URL: /api
