name: CI

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

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  verify:
    name: Typecheck, test & build
    runs-on: ubuntu-latest
    timeout-minutes: 25

    # Riktiga tjänster i CI: migrationer + seed körs mot Postgres 16 med
    # sök-extensions, precis som i produktion (i18n M7).
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_USER: app_user
          POSTGRES_PASSWORD: app_ci_password
          POSTGRES_DB: app_test
        options: >-
          --health-cmd "pg_isready -U app_user -d app_test"
          --health-interval 5s --health-timeout 5s --health-retries 10
      redis:
        image: redis:7-alpine
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 5s --health-timeout 5s --health-retries 10

    env:
      DATABASE_URL: postgres://app_user:app_ci_password@postgres:5432/app_test
      TEST_DATABASE_URL: postgres://app_user:app_ci_password@postgres:5432/app_test
      REDIS_URL: redis://redis:6379
      AAMOS_MODE: mock
      S3_MODE: mock
      EMAIL_MODE: log
      JWT_ACCESS_SECRET: ci-only-secret
      JWT_REFRESH_SECRET: ci-only-secret-two
      ENTITLEMENT_SIGNING_SECRET: ci-only-secret-three

    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Varumärkesvakt (namnet lever endast i brand.config.json)
        run: ./scripts/brand-guard.sh

      - name: Prettier
        run: pnpm format:check

      - name: Typecheck
        run: pnpm typecheck

      - name: i18n-vakt (alla språk kompletta, ingen hårdkodad UI-text)
        run: pnpm --filter @app/mobile i18n:check

      - name: Test
        run: pnpm test

      - name: Build
        run: pnpm build

      - name: Migrera + seeda mot riktig Postgres
        run: pnpm db:migrate && pnpm db:seed

      - name: API-röktest (boot + healthz + readyz)
        run: |
          node apps/api/dist/index.js &
          API_PID=$!
          for i in $(seq 1 20); do
            curl -fsS http://localhost:4000/healthz > /dev/null 2>&1 && break
            sleep 1
          done
          curl -fsS http://localhost:4000/healthz
          curl -fsS http://localhost:4000/readyz
          kill $API_PID
