# CI Arboretum : build + tests sur Node 22/24, puis smoke de packaging npx.
name: CI

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

permissions:
  contents: read

jobs:
  test:
    name: Build & test (Node ${{ matrix.node }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        node: [22, 24]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}
          cache: npm
      - run: npm ci
      - run: npm run typecheck
      - run: npm run build
      - run: npx vitest run

  pack-smoke:
    name: Pack & boot smoke (Node 22)
    runs-on: ubuntu-latest
    needs: test
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run build
      # @arboretum/shared (dépendance runtime non publiée) est embarquée dans le tarball
      # via bundleDependencies (matérialisée au prepack). On packe donc UN SEUL tarball
      # et on l'installe seul, comme un vrai consommateur depuis le registre.
      - name: Pack tarball
        run: |
          mkdir -p /tmp/tarballs
          npm pack -w @johanleroy/git-arboretum --pack-destination /tmp/tarballs
          ls -l /tmp/tarballs
      - name: Assert @arboretum/shared is bundled in the tarball
        run: |
          tgz=$(ls /tmp/tarballs/*.tgz)
          tar -tzf "$tgz" | grep -q 'node_modules/@arboretum/shared/dist/index.js' \
            || { echo "ERREUR: @arboretum/shared non embarqué dans $tgz"; exit 1; }
          echo "OK: bundleDependency @arboretum/shared présente dans $tgz"
      - name: Install tarball in an empty project
        run: |
          mkdir /tmp/smoke
          cd /tmp/smoke
          npm init -y
          npm i /tmp/tarballs/*.tgz
      - name: Boot smoke (expect 401 on /api/v1/sessions)
        run: |
          cd /tmp/smoke
          timeout 30 node_modules/.bin/arboretum --port 7999 --db ./t.db &
          server_pid=$!
          code=000
          for i in $(seq 1 20); do
            sleep 0.5
            code=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:7999/api/v1/sessions || true)
            if [ "$code" = "401" ]; then break; fi
          done
          echo "GET /api/v1/sessions -> HTTP $code"
          kill "$server_pid" 2>/dev/null || true
          test "$code" = "401"
