#!/usr/bin/env bash
# Publishes local DDS END USERs from CB_APP_USER and verifies the catalog.
# A live MCP call is optional and uses a bearer supplied only through .env.
set -Eeuo pipefail

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

[[ -f .env ]] || { echo '[FAIL] .env is required.' >&2; exit 1; }
set -a
# shellcheck disable=SC1091
. ./.env
set +a

if [[ -x "$ROOT/.tools/sqlcl-26.1.2/sqlcl/bin/sql" ]]; then
  SQL_CLIENT="$ROOT/.tools/sqlcl-26.1.2/sqlcl/bin/sql"
elif command -v sqlplus >/dev/null; then
  SQL_CLIENT="$(command -v sqlplus)"
else
  echo '[FAIL] SQLcl or sqlplus is required to run the ADB scenario.' >&2
  exit 1
fi
[[ -n "${ADB_USER:-}" && -n "${ADB_PASSWORD:-}" && -n "${ADB_TNS:-}" ]] \
  || { echo '[FAIL] ADB_USER, ADB_PASSWORD, and ADB_TNS are required.' >&2; exit 1; }

run_admin() {
  "$SQL_CLIENT" -S -L "${ADB_USER}/${ADB_PASSWORD}@${ADB_TNS}" @"$1"
}

run_admin "$ROOT/sql/adb/44_dds_mcp_local_end_user_setup.sql"
run_admin "$ROOT/sql/adb/45_dds_mcp_local_end_user_test.sql"

if [[ -z "${DDS_MCP_TEST_BEARER:-}" ]]; then
  echo '[OK] DDS END USER catalog scenario passed. Set DDS_MCP_TEST_BEARER to run the live MCP tool call.'
  exit 0
fi

BASE_URL="${DDS_MCP_BASE_URL:-http://127.0.0.1:${DDS_BACKOFFICE_PORT:-8083}}"
RESPONSE_FILE="$(mktemp /tmp/dds-mcp-end-user-response.XXXXXX)"
trap 'rm -f "$RESPONSE_FILE"' EXIT

curl -fsS --connect-timeout 5 --max-time 30 \
  -H "Authorization: Bearer ${DDS_MCP_TEST_BEARER}" \
  -H 'Content-Type: application/json' \
  --data '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"dds_vector_search","arguments":{"query":"DDS 검증 자료","limit":10,"embeddingMode":"DEMO"}}}' \
  -o "$RESPONSE_FILE" \
  "$BASE_URL/dds/mcp/messages"

rg -q '"isError"[[:space:]]*:[[:space:]]*false' "$RESPONSE_FILE" \
  || { echo '[FAIL] MCP tool call did not return a successful DDS result.' >&2; exit 1; }
echo '[OK] DDS END USER catalog and SSE MCP scenario passed.'
