name: CI/CD

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

env:
  NODE_VERSION: '20'

# Prevent concurrent runs on the same branch
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

# Least-privilege: only read repo contents; explicit permissions per job
permissions:
  contents: read

jobs:
  # ==================== 1. LINT & TEST ====================
  lint-and-test:
    name: Lint & Test
    runs-on: ubuntu-latest
    timeout-minutes: 15
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

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

      - run: npm ci --legacy-peer-deps

      - name: Generate Prisma Client
        run: npx prisma generate --schema=backend/libs/database/prisma/schema.prisma

      - name: Type check API
        run: cd backend/apps/api && npx tsc --noEmit -p tsconfig.json

      - name: Type check Realtime
        run: cd backend/apps/realtime && npx tsc --noEmit -p tsconfig.json

      - name: Type check Workers
        run: cd backend/apps/workers && npx tsc --noEmit -p tsconfig.json

      - name: Build Frontend
        run: cd frontend && npx next build

  # ==================== 2. SECURITY SCAN ====================
  security-scan:
    name: Security Scan (Trivy)
    runs-on: ubuntu-latest
    timeout-minutes: 10
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@v4

      - name: Run Trivy vulnerability scanner (repo + filesystem)
        uses: aquasecurity/trivy-action@0.28.0
        with:
          scan-type: 'fs'
          scan-ref: '.'
          severity: 'CRITICAL,HIGH'
          format: 'sarif'
          output: 'trivy-results.sarif'
          exit-code: '1'

      - name: Upload Trivy results to GitHub Security
        uses: github/codeql-action/upload-sarif@v3
        if: always()
        with:
          sarif_file: trivy-results.sarif

  # ==================== 3. BUILD & PUSH IMAGES ====================
  build-and-push:
    name: Build & Push Docker Images
    needs: [lint-and-test, security-scan]
    runs-on: ubuntu-latest
    timeout-minutes: 30
    if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop'
    permissions:
      contents: read
      packages: write
    strategy:
      matrix:
        service: [api, realtime, workers, frontend]
    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build ${{ matrix.service }}
        uses: docker/build-push-action@v5
        with:
          context: .
          file: backend/apps/${{ matrix.service }}/Dockerfile
          push: false
          tags: chatapp-${{ matrix.service }}:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: true
          sbom: true

      - name: Scan built image with Trivy
        uses: aquasecurity/trivy-action@0.28.0
        with:
          image-ref: chatapp-${{ matrix.service }}:${{ github.sha }}
          severity: 'CRITICAL,HIGH'
          format: 'table'
          exit-code: '1'

  # ==================== 4. DATABASE MIGRATIONS ====================
  migrate-database:
    name: Run Database Migrations
    needs: build-and-push
    runs-on: ubuntu-latest
    timeout-minutes: 10
    if: github.ref == 'refs/heads/main'
    environment: production
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
      - run: npm ci --legacy-peer-deps
      - name: Run migrations
        env:
          DATABASE_URL: ${{ secrets.PRODUCTION_DATABASE_URL }}
        run: npx prisma migrate deploy --schema=backend/libs/database/prisma/schema.prisma
      - name: Generate Prisma client
        run: npx prisma generate --schema=backend/libs/database/prisma/schema.prisma

  # ==================== 5. SMOKE TESTS ====================
  smoke-tests:
    name: Smoke Tests
    needs: migrate-database
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      contents: read
    steps:
      - name: Health check API
        run: |
          response=$(curl -s -o /dev/null -w "%{http_code}" https://api.chatapp.com/api/v1/health)
          if [ "$response" != "200" ]; then
            echo "API health check failed with status $response"
            exit 1
          fi
      - name: Health check Web
        run: |
          response=$(curl -s -o /dev/null -w "%{http_code}" https://app.chatapp.com)
          if [ "$response" != "200" ]; then
            echo "Web health check failed"
            exit 1
          fi