name: CI

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

env:
  NODE_OPTIONS: --dns-result-order=ipv4first

defaults:
  run:
    shell: bash

jobs:
  build-and-anchors:
    runs-on: mac-ci
    container:
      image: mcr.microsoft.com/devcontainers/javascript-node:22-bookworm

    steps:
      - name: Tools sanity
        run: |
          set -euo pipefail
          git --version
          node --version
          npm --version
          npm ping --registry=https://registry.npmjs.org

      - name: Checkout (from event.json, no external actions)
        run: |
          set -euo pipefail
          export EVENT_JSON="/var/run/act/workflow/event.json"
          test -f "$EVENT_JSON" || { echo "❌ Missing $EVENT_JSON"; exit 1; }

          eval "$(node --input-type=module -e 'import fs from "node:fs";
            const ev = JSON.parse(fs.readFileSync(process.env.EVENT_JSON,"utf8"));
            const repo =
              ev?.repository?.clone_url ||
              (ev?.repository?.html_url ? (ev.repository.html_url.replace(/\/$/,"") + ".git") : "");
            const sha =
              ev?.after ||
              ev?.pull_request?.head?.sha ||
              ev?.head_commit?.id ||
              ev?.sha ||
              "";
            if (!repo) throw new Error("No repository url in event.json");
            if (!sha)  throw new Error("No sha in event.json");
            process.stdout.write(`REPO_URL=${JSON.stringify(repo)}\nSHA=${JSON.stringify(sha)}\n`);
          ')"

          echo "Repo URL: $REPO_URL"
          echo "SHA:      $SHA"

          rm -rf .git
          git init -q
          git remote add origin "$REPO_URL"
          git fetch --depth 1 origin "$SHA"
          git -c advice.detachedHead=false checkout -q FETCH_HEAD
          git log -1 --oneline

      - name: Anchor aliases schema
        run: |
          set -euo pipefail
          node scripts/check-anchor-aliases.mjs

      - name: NPM harden
        run: |
          set -euo pipefail
          npm config set fetch-retries 5
          npm config set fetch-retry-mintimeout 20000
          npm config set fetch-retry-maxtimeout 120000
          npm config set registry https://registry.npmjs.org
          npm config get registry

      - name: Install deps
        run: |
          set -euo pipefail
          npm ci

      - name: Full test suite (CI=1)
        run: |
          set -euo pipefail
          npm run ci
