name: CI

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

jobs:
  build:
    # Host-mode runner (docker talks to the host daemon). We publish a pgvector
    # Postgres to localhost:5434 and connect over localhost — the service-name
    # networking of `services:` containers is not wired to jobs on this runner,
    # so we start the DB explicitly (same proven pattern as the mdm CI).
    runs-on: dind-builder
    env:
      DATABASE_URL: postgresql://iios:iios@localhost:5434/iios?schema=public
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
        with:
          version: 10
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: pnpm

      # pgvector Postgres for the DB-backed *.spec.ts integration suites.
      - name: Start pgvector Postgres
        run: |
          docker rm -f iios-ci-pg-${{ github.run_id }} >/dev/null 2>&1 || true
          docker run -d --name iios-ci-pg-${{ github.run_id }} \
            -e POSTGRES_USER=iios -e POSTGRES_PASSWORD=iios -e POSTGRES_DB=iios \
            -p 5434:5432 pgvector/pgvector:pg16
          for i in $(seq 1 30); do
            docker exec iios-ci-pg-${{ github.run_id }} pg_isready -U iios >/dev/null 2>&1 && break
            sleep 2
          done
          docker exec iios-ci-pg-${{ github.run_id }} pg_isready -U iios \
            || { echo "Postgres did not become ready"; exit 1; }

      - run: pnpm install --frozen-lockfile
      - run: pnpm boundary
      # iios-service uses Prisma: generate the client so its generated types
      # (schema enums, Prisma.InputJsonValue) are available for typecheck/build.
      - run: pnpm --filter @insignia/iios-service prisma:generate
      # Build before typecheck: the @insignia/* workspace packages publish their
      # types via built dist/*.d.ts, so consumers (iios-kernel-client, etc.)
      # can only resolve them once dist exists. Typechecking first fails with
      # TS2307 "Cannot find module '@insignia/iios-contracts'".
      - run: pnpm -r build
      - run: pnpm -r typecheck
      # Apply the schema to the CI Postgres before the DB-backed specs run
      # (reset-db.ts TRUNCATEs existing tables; migrations must exist first).
      - run: pnpm --filter @insignia/iios-service exec prisma migrate deploy
      - run: pnpm test

      - name: Stop Postgres
        if: always()
        run: docker rm -f iios-ci-pg-${{ github.run_id }} >/dev/null 2>&1 || true
