-- ============================================================================
-- MARS-826 Rollback Script
-- ============================================================================
-- Purpose: Remove exported historical data from HIST bucket
-- Author: Grzegorz Michalski
-- Schema: OU_LM, OU_MRR (source schemas - read-only)
-- Target: HIST bucket cleanup (delete exported Parquet files)
-- Date: 2025-12-02
-- ============================================================================

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

-- Dynamic spool file generation (using SYS_CONTEXT - no DBA privileges required)
-- Log files are automatically created in log/ subdirectory
var filename VARCHAR2(100)
BEGIN
    :filename := 'log/ROLLBACK_MARS_826_' || SYS_CONTEXT('USERENV', 'CON_NAME') || '_' || TO_CHAR(SYSDATE,'YYYYMMDD_HH24MISS') || '.log';
END;
/
column filename new_value _filename
select :filename filename from dual;
spool &_filename

SET ECHO OFF
SET TIMING ON
SET SERVEROUTPUT ON SIZE UNLIMITED
SET PAUSE OFF

PROMPT ============================================================================
PROMPT MARS-826 Rollback - Remove Exported Historical Data
PROMPT ============================================================================
PROMPT
PROMPT This rollback will DELETE all exported Parquet files from HIST bucket.
PROMPT 
PROMPT Tables affected: 19 tables from OU_LM and OU_MRR schemas
PROMPT Bucket location: history/ARCHIVE/LM/
PROMPT
PROMPT ============================================================================
ACCEPT confirmation CHAR PROMPT 'Do you want to proceed with rollback? (YES/NO): '

WHENEVER SQLERROR EXIT SQL.SQLCODE

-- Validate confirmation
BEGIN
    IF UPPER('&confirmation') != 'YES' THEN
        RAISE_APPLICATION_ERROR(-20001, 'Rollback cancelled by user');
    END IF;
END;
/

PROMPT
PROMPT Starting rollback execution...
PROMPT Timestamp: 
SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS ROLLBACK_START FROM DUAL;
PROMPT
PROMPT ============================================================================

-- Execute rollback scripts
@@91_MARS_826_rollback_ADHOC_ADJ_tables.sql
@@92_MARS_826_rollback_BALANCESHEET_tables.sql
@@93_MARS_826_rollback_CSM_ADJ_tables.sql
@@94_MARS_826_rollback_STANDING_FACILITY_tables.sql
@@95_MARS_826_rollback_MRR_IND_CURRENT_ACCOUNT_tables.sql
@@96_MARS_826_rollback_FORECAST_tables.sql
@@97_MARS_826_rollback_QR_ADJ_tables.sql
@@98_MARS_826_rollback_TTS_tables.sql
@@99_MARS_826_verify_rollback.sql

PROMPT
PROMPT ============================================================================
PROMPT Rollback completed successfully
PROMPT Timestamp: 
SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS ROLLBACK_END FROM DUAL;
PROMPT ============================================================================

spool off

quit;
