-- ============================================================================
-- MARS-1409-POSTHOOK Master Rollback Script
-- ============================================================================
-- Purpose: Rollback MARS-1409-POSTHOOK - Clear backfilled A_WORKFLOW_HISTORY_KEY
--          values from A_SOURCE_FILE_RECEIVED.
-- Author: Grzegorz Michalski
-- Date: 2026-03-13
-- Note: This clears ALL non-NULL A_WORKFLOW_HISTORY_KEY values. The trigger
--       installed by MARS-1409 will repopulate them on next file processing.
-- ============================================================================

SET SERVEROUTPUT ON SIZE UNLIMITED
SET VERIFY OFF
SET FEEDBACK ON
SET ECHO OFF

-- Create log directory if it doesn't exist
host mkdir log 2>nul

-- Generate dynamic SPOOL filename with timestamp
var filename VARCHAR2(100)
BEGIN
    :filename := 'log/ROLLBACK_MARS_1409_POSTHOOK_' || SYS_CONTEXT('USERENV', 'CON_NAME') || '_' || TO_CHAR(SYSDATE,'YYYYMMDD_HH24MISS') || '.log';
END;
/
column filename new_value _filename
select :filename filename from dual;
spool &_filename

PROMPT
PROMPT ============================================================================
PROMPT MARS-1409-POSTHOOK Rollback Starting
PROMPT ============================================================================
PROMPT This will reverse all changes from MARS-1409-POSTHOOK installation.
PROMPT
PROMPT Rollback steps:
PROMPT 1. Clear A_WORKFLOW_HISTORY_KEY values from A_SOURCE_FILE_RECEIVED
PROMPT ============================================================================

-- Confirm rollback with user
ACCEPT continue CHAR PROMPT 'Type YES to continue with rollback, or Ctrl+C to abort: '
WHENEVER SQLERROR EXIT SQL.SQLCODE
BEGIN
    IF '&continue' IS NULL OR TRIM('&continue') IS NULL OR UPPER(TRIM('&continue')) != 'YES' THEN
        RAISE_APPLICATION_ERROR(-20000, 'Rollback aborted by user');
    END IF;
END;
/
WHENEVER SQLERROR CONTINUE

PROMPT
PROMPT ============================================================================
PROMPT STEP 1: Clear backfilled A_WORKFLOW_HISTORY_KEY values
PROMPT ============================================================================
@@91_MARS_1409_POSTHOOK_rollback_workflow_keys.sql

PROMPT
PROMPT ============================================================================
PROMPT MARS-1409-POSTHOOK Rollback Complete
PROMPT ============================================================================
PROMPT Final Status:
SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS rollback_end FROM DUAL;
PROMPT
PROMPT Review the log file for detailed results: &_filename
PROMPT ============================================================================

spool off

quit;
