-- ============================================================
-- 52_cleanup_to_kb_vpd_poc.sql
--
-- Removes legacy document/Vector/DDS/test examples and keeps only
-- the KB structured-data VPD POC:
--   POC_2.KB_* seven ledgers, stakeholder identity, KB roles,
--   bearer-token permission metadata, and their VPD policies.
--
-- Oracle-maintained ANNOTATIONS_* / VECTOR$* auxiliary objects are
-- not dropped directly.  Their owning RAG/vector tables are dropped.
-- ============================================================
WHENEVER SQLERROR EXIT SQL.SQLCODE
SET ECHO OFF
SET FEEDBACK ON
SET DEFINE OFF
SET SERVEROUTPUT ON
ALTER SESSION DISABLE PARALLEL DML;

PROMPT === 1. Removing document, legacy role, and test permissions ===
DECLARE
  c_role_keep_1 CONSTANT VARCHAR2(80) := 'KB_DESIGNER_ROLE';
  c_role_keep_2 CONSTANT VARCHAR2(80) := 'KB_BRANCH_MANAGER_ROLE';
  c_role_keep_3 CONSTANT VARCHAR2(80) := 'KB_STAKEHOLDER_IDENTITY_ROLE';
  c_role_keep_4 CONSTANT VARCHAR2(80) := 'KB_VPD_ADMIN_ROLE';
BEGIN
  DELETE FROM cb_permission_column
  WHERE permission_id IN (
    SELECT p.perm_id
    FROM cb_permission p
    JOIN cb_app_role r ON r.role_id = p.role_id
    WHERE r.role_name NOT IN (c_role_keep_1, c_role_keep_2, c_role_keep_3, c_role_keep_4)
       OR p.target_name NOT IN (
         'KB_CUSTOMERS', 'KB_PRODUCTS', 'KB_CONTRACTS', 'KB_COVERAGES',
         'KB_CLAIMS', 'KB_EXTERNAL_HOLDINGS', 'KB_STAKEHOLDERS'
       )
  );

  DELETE FROM cb_permission_rule
  WHERE perm_id IN (
    SELECT p.perm_id
    FROM cb_permission p
    JOIN cb_app_role r ON r.role_id = p.role_id
    WHERE r.role_name NOT IN (c_role_keep_1, c_role_keep_2, c_role_keep_3, c_role_keep_4)
       OR p.target_name NOT IN (
         'KB_CUSTOMERS', 'KB_PRODUCTS', 'KB_CONTRACTS', 'KB_COVERAGES',
         'KB_CLAIMS', 'KB_EXTERNAL_HOLDINGS', 'KB_STAKEHOLDERS'
       )
  );

  DELETE FROM cb_permission
  WHERE perm_id IN (
    SELECT p.perm_id
    FROM cb_permission p
    JOIN cb_app_role r ON r.role_id = p.role_id
    WHERE r.role_name NOT IN (c_role_keep_1, c_role_keep_2, c_role_keep_3, c_role_keep_4)
       OR p.target_name NOT IN (
         'KB_CUSTOMERS', 'KB_PRODUCTS', 'KB_CONTRACTS', 'KB_COVERAGES',
         'KB_CLAIMS', 'KB_EXTERNAL_HOLDINGS', 'KB_STAKEHOLDERS'
       )
  );

  DELETE FROM cb_user_role
  WHERE role_id IN (
    SELECT role_id
    FROM cb_app_role
    WHERE role_name NOT IN (c_role_keep_1, c_role_keep_2, c_role_keep_3, c_role_keep_4)
  );

  DELETE FROM cb_group_role;
  DELETE FROM cb_user_group;
  DELETE FROM cb_app_group;

  DELETE FROM cb_app_role
  WHERE role_name NOT IN (c_role_keep_1, c_role_keep_2, c_role_keep_3, c_role_keep_4);

  -- Keep only tokens attached to an actual KB stakeholder.
  DELETE FROM cb_agent_bearer_key
  WHERE stakeholder_user_id IS NULL;

  -- Non-stakeholder users were document/test sample principals.
  DELETE FROM cb_app_user
  WHERE stakeholder_user_id IS NULL;

  DELETE FROM cb_vpd_filter_note;
  DELETE FROM cb_vpd_policy_note;
  DELETE FROM cb_ords_probe_audit;

  DELETE FROM cb_protected_column
  WHERE object_id IN (
    SELECT object_id
    FROM cb_protected_object
    WHERE NOT (
      owner = 'POC_2'
      AND object_name IN (
        'KB_CUSTOMERS', 'KB_PRODUCTS', 'KB_CONTRACTS', 'KB_COVERAGES',
        'KB_CLAIMS', 'KB_EXTERNAL_HOLDINGS', 'KB_STAKEHOLDERS'
      )
    )
  );

  DELETE FROM cb_protected_object
  WHERE NOT (
    owner = 'POC_2'
    AND object_name IN (
      'KB_CUSTOMERS', 'KB_PRODUCTS', 'KB_CONTRACTS', 'KB_COVERAGES',
      'KB_CLAIMS', 'KB_EXTERNAL_HOLDINGS', 'KB_STAKEHOLDERS'
    )
  );

  COMMIT;
END;
/

PROMPT === 2. Removing legacy document VPD/redaction and source objects ===
BEGIN
  DBMS_REDACT.DROP_POLICY(
    object_schema => 'ADMIN',
    object_name   => 'CB_V_SEARCH_DOCUMENTS',
    policy_name   => 'CB_CONTENTS_REDACT'
  );
EXCEPTION
  WHEN OTHERS THEN
    -- The policy may already be absent in a reduced POC schema.
    DBMS_OUTPUT.PUT_LINE('redaction policy not removed: ' || SQLERRM);
END;
/

DECLARE
  v_count NUMBER;
BEGIN
  SELECT COUNT(*)
  INTO   v_count
  FROM   all_policies
  WHERE  object_owner = 'ADMIN'
  AND    object_name = 'CB_V_SEARCH_DOCUMENTS'
  AND    policy_name = 'CB_AGENT_DOC_POLICY';

  IF v_count > 0 THEN
    DBMS_RLS.DROP_POLICY(
      object_schema => 'ADMIN',
      object_name   => 'CB_V_SEARCH_DOCUMENTS',
      policy_name   => 'CB_AGENT_DOC_POLICY'
    );
  END IF;
END;
/

BEGIN
  EXECUTE IMMEDIATE 'DROP VIEW cb_v_search_documents';
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -942 THEN
      RAISE;
    END IF;
END;
/

BEGIN
  EXECUTE IMMEDIATE 'DROP TABLE cb_search_documents PURGE';
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -942 THEN
      RAISE;
    END IF;
END;
/

PROMPT === 3. Dropping unrelated POC_2 backup, RAG, and security-example tables ===
DECLARE
  PROCEDURE drop_table_if_exists(p_table_name IN VARCHAR2) IS
  BEGIN
    EXECUTE IMMEDIATE
      'DROP TABLE POC_2.' || DBMS_ASSERT.SIMPLE_SQL_NAME(p_table_name)
      || ' CASCADE CONSTRAINTS PURGE';
    DBMS_OUTPUT.PUT_LINE('dropped POC_2.' || p_table_name);
  EXCEPTION
    WHEN OTHERS THEN
      IF SQLCODE = -942 THEN
        NULL;
      ELSE
        RAISE;
      END IF;
  END;
BEGIN
  drop_table_if_exists('BKP_CLM_20260701144052');
  drop_table_if_exists('BKP_CONT_20260701144052');
  drop_table_if_exists('BKP_COV_20260701144052');
  drop_table_if_exists('BKP_CUST_20260701144052');
  drop_table_if_exists('BKP_EXT_20260701144052');
  drop_table_if_exists('BKP_PROD_20260701144052');
  drop_table_if_exists('KB_CUST_BAK_202607011343');
  drop_table_if_exists('KB_CUST_BAK_20260701134439');
  drop_table_if_exists('KB_AIDP_RAG_CORPUS_CONFIG');
  drop_table_if_exists('KB_AIDP_RAG_QUERY_CACHE');
  drop_table_if_exists('KB_COMPETITOR_TERMS_CHUNKS');
  drop_table_if_exists('KB_COMPETITOR_TERMS_DOCUMENTS');
  drop_table_if_exists('KB_OWN_TERMS_CHUNKS');
  drop_table_if_exists('KB_OWN_TERMS_DOCUMENTS');
  drop_table_if_exists('KB_SECURITY_AUDIT_LOG');
  drop_table_if_exists('KB_SECURITY_POLICY_CATALOG');
END;
/

PROMPT === 4. Remaining KB VPD POC inventory ===
SELECT object_name
FROM cb_protected_object
WHERE owner = 'POC_2'
ORDER BY object_name;

SELECT role_name
FROM cb_app_role
ORDER BY role_name;

SELECT key_id, stakeholder_user_id, key_prefix, active, expires_at
FROM cb_agent_bearer_key
ORDER BY key_id;

SELECT object_owner, object_name, policy_name, function, enable
FROM all_policies
WHERE object_owner = 'POC_2'
ORDER BY object_name, policy_name;

PROMPT === KB VPD POC cleanup complete ===
