-- ============================================================
-- 53_drop_legacy_poc_objects.sql
-- Completes the physical-object portion of the KB VPD POC cleanup
-- after 52 has removed legacy permissions, roles, tokens and users.
-- ============================================================
WHENEVER SQLERROR EXIT SQL.SQLCODE
SET ECHO OFF
SET FEEDBACK ON
SET DEFINE OFF
SET SERVEROUTPUT ON

PROMPT === 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
    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 === 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 === Legacy physical objects removed ===
