name: IAM Service CI

on:
  push:
    paths:
      - 'services/iam-service/**'
      - 'packages/**'
  pull_request:
    paths:
      - 'services/iam-service/**'
      - 'packages/**'

jobs:
  lint-and-test:
    runs-on: ubuntu-latest
    
    # Use Neon test database if available, otherwise use PostgreSQL service
    services:
      postgres:
        image: postgres:16-alpine
        env:
          POSTGRES_USER: testuser
          POSTGRES_PASSWORD: testpass
          POSTGRES_DB: test_db
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432
    
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup PNPM
        uses: pnpm/action-setup@v2
        with:
          version: 8
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '25'
          cache: 'pnpm'
      
      - name: Install dependencies
        run: pnpm install --frozen-lockfile
      
      - name: Build shared packages
        run: pnpm --filter './packages/*' build
      
      - name: Generate Prisma Client
        run: pnpm --filter @goodgo/iam-service prisma:generate
        env:
          # Use Neon test DB if available, otherwise fallback to local PostgreSQL
          DATABASE_URL: ${{ secrets.NEON_DATABASE_URL_TEST != '' && secrets.NEON_DATABASE_URL_TEST || 'postgresql://testuser:testpass@localhost:5432/test_db' }}
      
      - name: Run migrations
        run: pnpm --filter @goodgo/iam-service prisma migrate deploy
        env:
          DATABASE_URL: ${{ secrets.NEON_DATABASE_URL_TEST != '' && secrets.NEON_DATABASE_URL_TEST || 'postgresql://testuser:testpass@localhost:5432/test_db' }}
      
      - name: Lint
        run: pnpm --filter @goodgo/iam-service lint
      
      - name: Type check
        run: pnpm --filter @goodgo/iam-service typecheck
      
      - name: Build
        run: pnpm --filter @goodgo/iam-service build
      
      - name: Test
        run: pnpm --filter @goodgo/iam-service test
        env:
          DATABASE_URL: ${{ secrets.NEON_DATABASE_URL_TEST != '' && secrets.NEON_DATABASE_URL_TEST || 'postgresql://testuser:testpass@localhost:5432/test_db' }}
