-- ============================================================
-- 45_dds_mcp_local_end_user_test.sql
-- Catalog-level acceptance test for 44. Run as ADMIN.
-- The SSE/JDBC context assertion is performed by dds_vector_search after
-- the OCI IAM database-access token configuration is supplied.
-- ============================================================
WHENEVER SQLERROR EXIT SQL.SQLCODE
SET ECHO OFF
SET FEEDBACK ON
SET LINESIZE 220
SET PAGESIZE 200

DECLARE
  v_missing_map NUMBER;
  v_missing_end_user NUMBER;
  v_missing_role NUMBER;
BEGIN
  SELECT COUNT(*) INTO v_missing_map
  FROM cb_app_user u
  LEFT JOIN cb_dds_end_user_map m ON m.application_user_id = u.user_id
  WHERE u.active = 'Y'
    AND (m.application_user_id IS NULL OR m.publish_status <> 'PUBLISHED');

  SELECT COUNT(*) INTO v_missing_end_user
  FROM cb_dds_end_user_map m
  JOIN cb_app_user u ON u.user_id = m.application_user_id AND u.active = 'Y'
  LEFT JOIN dba_end_users eu ON eu.username = m.end_user_name
  WHERE eu.username IS NULL;

  SELECT COUNT(*) INTO v_missing_role
  FROM cb_dds_end_user_map m
  JOIN cb_app_user u ON u.user_id = m.application_user_id AND u.active = 'Y'
  LEFT JOIN dba_data_role_grants rg
    ON rg.grantee = m.end_user_name
   AND rg.data_role = m.data_role_name
  WHERE rg.data_role IS NULL;

  IF v_missing_map <> 0 OR v_missing_end_user <> 0 OR v_missing_role <> 0 THEN
    RAISE_APPLICATION_ERROR(-20944,
      'DDS MCP publish validation failed: map=' || v_missing_map
      || ', end_user=' || v_missing_end_user || ', data_role=' || v_missing_role);
  END IF;
END;
/

COLUMN user_name FORMAT A22
COLUMN end_user_name FORMAT A18
COLUMN data_role_name FORMAT A24
COLUMN grant_name FORMAT A34
SELECT u.user_name, m.end_user_name, m.data_role_name, m.grant_name,
       CASE WHEN dg.grant_name IS NULL THEN 'DEFAULT_DENY' ELSE 'PUBLISHED' END AS vector_access
FROM cb_dds_end_user_map m
JOIN cb_app_user u ON u.user_id = m.application_user_id
LEFT JOIN dba_data_grants dg ON dg.grant_name = m.grant_name
WHERE u.active = 'Y'
ORDER BY m.application_user_id;

PROMPT Catalog validation passed. Next: call /dds/mcp/sse and dds_vector_search with a valid MCP Bearer.
EXIT;
