#!/usr/bin/env bash
# KB 역할(RBAC) + 속성(ABAC) MCP 검증 로그
#
# Required business bearer tokens:
#   FC00789_TOKEN  담당설계사 FC00789
#   FC00833_TOKEN  타설계사 FC00833
#   MGR_GN01_TOKEN 지점장 MGR_GN01 (설계사채널)
#
# MCP access token defaults to ~/.config/codex/vpd-mcp.env.
# It is separate from the three business bearer tokens above.
set -Eeuo pipefail

if [[ -f "${HOME}/.config/codex/vpd-mcp.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  . "${HOME}/.config/codex/vpd-mcp.env"
  set +a
fi

: "${VPD_MCP_ACCESS_TOKEN:?VPD_MCP_ACCESS_TOKEN이 필요합니다.}"
: "${FC00789_TOKEN:?FC00789_TOKEN이 필요합니다.}"
: "${FC00833_TOKEN:?FC00833_TOKEN이 필요합니다.}"
: "${MGR_GN01_TOKEN:?MGR_GN01_TOKEN이 필요합니다.}"

MCP_URL="${VPD_MCP_URL:-https://kb.cloud-handson.com/mcp}"

call_tool() {
  local scenario="$1"
  local token="$2"
  local tool_name="$3"

  jq -n --arg name "$tool_name" --arg token "$token" '
    {
      jsonrpc: "2.0",
      id: 1,
      method: "tools/call",
      params: {
        name: $name,
        arguments: {bearerToken: $token, limit: 100}
      }
    }
  ' | curl -ksS --fail --connect-timeout 5 --max-time 45 \
      -H "Authorization: Bearer ${VPD_MCP_ACCESS_TOKEN}" \
      -H 'Content-Type: application/json' \
      --data @- "$MCP_URL" \
    | jq -r --arg scenario "$scenario" '
        (.result.content[0].text | fromjson) as $result
        | ($result.maskedColumns // [] | join(", ")) as $masked
        | "[" + $scenario + "]\n"
          + "  대상: " + $result.object + "\n"
          + "  결과: " + $result.status + ", 조회 " + ($result.rowCount | tostring) + "건\n"
          + "  NULL 처리 컬럼: " + (if $masked == "" then "없음" else $masked end) + "\n"
      '
}

echo '[KB RBAC/ABAC MCP 검증 시작]'
call_tool '담당설계사 FC00789 · 본인 계약' "$FC00789_TOKEN" 'ords.query.poc_2.kb_contracts'
call_tool '담당설계사 FC00789 · 담당 고객' "$FC00789_TOKEN" 'ords.query.poc_2.kb_customers'
call_tool '담당설계사 FC00789 · 담당 고객 청구' "$FC00789_TOKEN" 'ords.query.poc_2.kb_claims'
call_tool '담당설계사 FC00789 · 담당 고객 외부보유' "$FC00789_TOKEN" 'ords.query.poc_2.kb_external_holdings'
call_tool '타설계사 FC00833 · 본인 계약만' "$FC00833_TOKEN" 'ords.query.poc_2.kb_contracts'
call_tool '지점장 MGR_GN01 · 설계사채널 계약' "$MGR_GN01_TOKEN" 'ords.query.poc_2.kb_contracts'
call_tool '지점장 MGR_GN01 · 설계사채널 고객' "$MGR_GN01_TOKEN" 'ords.query.poc_2.kb_customers'
echo '[KB RBAC/ABAC MCP 검증 완료]'
