#!/usr/bin/env bash
set -euo pipefail

# Ensures packages/domain/dist stays in sync with source.
# Intended for CI or local verification before pushing.

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT_DIR"

echo "[domain] Building @customer-portal/domain…"
pnpm --filter @customer-portal/domain build >/dev/null

echo "[domain] Checking exports contract…"
node ./scripts/domain/check-exports.mjs

echo "[domain] Checking import contract…"
bash ./scripts/domain/check-import-contract.sh

if command -v git >/dev/null 2>&1; then
  if git diff --quiet -- packages/domain/dist; then
    echo "[domain] OK: packages/domain/dist is up to date."
    exit 0
  fi

  echo "[domain] ERROR: packages/domain/dist is out of sync with source."
  echo "[domain] Run: pnpm --filter @customer-portal/domain build"
  echo "[domain] Then commit the updated dist outputs."
  git --no-pager diff -- packages/domain/dist | head -200
  exit 1
fi

echo "[domain] WARNING: git not found; cannot verify dist drift. Build completed."

