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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
guardrail="${repo_root}/guardrails/store/check-api-dto-store-boundary.sh"
fixture_root="$(mktemp -d)"

cleanup() {
  rm -r "${fixture_root}"
}
trap cleanup EXIT

mkdir -p "${fixture_root}/internal/api/dto/converter"
cat >"${fixture_root}/internal/api/dto/request.go" <<'EOF'
package dto

import _ "github.com/tidbcloud/AgentTeam/internal/store/message"
EOF
cat >"${fixture_root}/internal/api/dto/converter/message.go" <<'EOF'
package converter

import _ "github.com/tidbcloud/AgentTeam/internal/store/message"
EOF

set +e
output="$({
  STORE_REFACTOR_API_DTO_ROOT="${fixture_root}/internal/api/dto" \
    STORE_REFACTOR_MAX_API_DTO_STORE_REFS=0 \
    bash "${guardrail}"
} 2>&1)"
exit_code=$?
set -e

if (( exit_code == 0 )); then
  echo "error: expected one non-converter DTO store reference to fail" >&2
  exit 1
fi
if ! grep -Fq 'internal/api/dto store refs (target 0): 1 (max 0)' <<<"${output}"; then
  echo "error: expected exactly one DTO store reference, got:" >&2
  printf '%s\n' "${output}" >&2
  exit 1
fi
if ! grep -Fq 'increased above allowed baseline (1 > 0)' <<<"${output}"; then
  echo "error: expected the zero ratchet to reject the reference, got:" >&2
  printf '%s\n' "${output}" >&2
  exit 1
fi

echo "api DTO store boundary guardrail regression: ok"
