-- ============================================================================
-- MARS-1409 Rollback 91A: Clear A_WORKFLOW_HISTORY_KEY for existing records
-- ============================================================================
-- Purpose: Set A_WORKFLOW_HISTORY_KEY to NULL for all existing records
--          This is part of rollback process - restores state before migration
-- Note: Cannot restore exact previous values (we don't track which were NULL)
--       This script sets ALL values to NULL to ensure clean rollback state
-- ============================================================================

SET SERVEROUTPUT ON SIZE UNLIMITED

PROMPT
PROMPT Clearing A_WORKFLOW_HISTORY_KEY for all A_SOURCE_FILE_RECEIVED records...

DECLARE
    vTotalRecords    NUMBER := 0;
    vClearedRecords  NUMBER := 0;
    
BEGIN
    -- Count total records
    SELECT COUNT(*) INTO vTotalRecords
    FROM CT_MRDS.A_SOURCE_FILE_RECEIVED;
    
    DBMS_OUTPUT.PUT_LINE('Total records in A_SOURCE_FILE_RECEIVED: ' || vTotalRecords);
    DBMS_OUTPUT.PUT_LINE('----------------------------------------');
    
    -- Clear A_WORKFLOW_HISTORY_KEY for all records
    UPDATE CT_MRDS.A_SOURCE_FILE_RECEIVED
    SET A_WORKFLOW_HISTORY_KEY = NULL
    WHERE A_WORKFLOW_HISTORY_KEY IS NOT NULL;
    
    vClearedRecords := SQL%ROWCOUNT;
    
    COMMIT;
    
    DBMS_OUTPUT.PUT_LINE('Rollback Summary:');
    DBMS_OUTPUT.PUT_LINE('  Records with A_WORKFLOW_HISTORY_KEY cleared: ' || vClearedRecords);
    DBMS_OUTPUT.PUT_LINE('  Records already NULL: ' || (vTotalRecords - vClearedRecords));
    DBMS_OUTPUT.PUT_LINE('----------------------------------------');
    DBMS_OUTPUT.PUT_LINE('NOTE: All A_WORKFLOW_HISTORY_KEY values set to NULL');
    DBMS_OUTPUT.PUT_LINE('      Original values cannot be restored (not tracked before migration)');
    
EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
        DBMS_OUTPUT.PUT_LINE('ERROR: ' || SQLERRM);
        DBMS_OUTPUT.PUT_LINE('Transaction rolled back');
        RAISE;
END;
/

PROMPT
PROMPT Workflow keys cleared successfully!
PROMPT
