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

# Guardrail: enforce the domain import contract.
#
# Allowed:
# - @customer-portal/domain/<module>
# - @customer-portal/domain/toolkit
# - BFF-only: @customer-portal/domain/<module>/providers
#
# Never:
# - @customer-portal/domain/<module>/<anything-else>
# - @customer-portal/domain/<module>/providers/<anything-else>
# - Portal importing any .../providers

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

fail() {
  echo "[domain] ERROR: $1" >&2
  exit 1
}

echo "[domain] Checking for illegal deep imports in apps/…"

# Root import is forbidden (hard error). Only match actual import statements.
if grep -RInE --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=.next \
  --include='*.ts' --include='*.tsx' \
  "(from[[:space:]]+[\"']@customer-portal/domain[\"'])|(import[[:space:]]+[\"']@customer-portal/domain[\"'])" \
  apps >/dev/null; then
  echo "[domain] Found forbidden root imports (@customer-portal/domain):"
  grep -RInE --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=.next \
    --include='*.ts' --include='*.tsx' \
    "(from[[:space:]]+[\"']@customer-portal/domain[\"'])|(import[[:space:]]+[\"']@customer-portal/domain[\"'])" \
    apps | head -200
  fail "Root import is forbidden. Use @customer-portal/domain/<module>."
fi

# Any 3+ segment import like @customer-portal/domain/a/b/c is illegal anywhere.
if grep -RInE --include='*.ts' --include='*.tsx' \
  "@customer-portal/domain/[^\"'[:space:]]+/[^\"'[:space:]]+/[^\"'[:space:]]+" \
  apps >/dev/null; then
  echo "[domain] Found illegal deep imports (3+ segments):"
  grep -RInE --include='*.ts' --include='*.tsx' \
    "@customer-portal/domain/[^\"'[:space:]]+/[^\"'[:space:]]+/[^\"'[:space:]]+" \
    apps | head -200
  fail "Deep imports detected. Use @customer-portal/domain/<module> or .../<module>/providers."
fi

echo "[domain] Checking Portal boundary (no providers imports)…"

if grep -RInE --include='*.ts' --include='*.tsx' \
  "@customer-portal/domain/[^\"'[:space:]]+/providers" \
  apps/portal/src >/dev/null; then
  echo "[domain] Found provider imports in Portal:"
  grep -RInE --include='*.ts' --include='*.tsx' \
    "@customer-portal/domain/[^\"'[:space:]]+/providers" \
    apps/portal/src | head -200
  fail "Portal must not import provider adapters/types."
fi

echo "[domain] OK: import contract checks passed."


