-- ====================================================================
-- MARS-835-PREHOOK ROLLBACK: Revert A_SOURCE_FILE_RECEIVED Table Structure
-- ====================================================================
-- Purpose: 
--   1. Rename column ARCH_PATH back to ARCH_FILE_NAME
--   2. Remove column PROCESS_NAME
-- Author: Grzegorz Michalski
-- Date: 2026-02-13
-- ====================================================================

SET SERVEROUTPUT ON SIZE UNLIMITED
SET TIMING ON

PROMPT ====================================================================
PROMPT MARS-835-PREHOOK ROLLBACK: Reverting A_SOURCE_FILE_RECEIVED table
PROMPT ====================================================================

DECLARE
    v_column_exists NUMBER;
    v_process_name_exists NUMBER;
BEGIN
    -- Check if ARCH_PATH exists (needs to be renamed back)
    SELECT COUNT(*)
    INTO v_column_exists
    FROM dba_tab_columns
    WHERE owner = 'CT_MRDS'
      AND table_name = 'A_SOURCE_FILE_RECEIVED'
      AND column_name = 'ARCH_PATH';
    
    IF v_column_exists > 0 THEN
        DBMS_OUTPUT.PUT_LINE('INFO: Renaming column ARCH_PATH back to ARCH_FILE_NAME...');
        EXECUTE IMMEDIATE 'ALTER TABLE CT_MRDS.A_SOURCE_FILE_RECEIVED RENAME COLUMN ARCH_PATH TO ARCH_FILE_NAME';
        DBMS_OUTPUT.PUT_LINE('SUCCESS: Column renamed back to ARCH_FILE_NAME');
    ELSE
        DBMS_OUTPUT.PUT_LINE('INFO: Column ARCH_PATH does not exist (already rolled back)');
    END IF;
    
    -- Check if PROCESS_NAME exists (needs to be dropped)
    SELECT COUNT(*)
    INTO v_process_name_exists
    FROM dba_tab_columns
    WHERE owner = 'CT_MRDS'
      AND table_name = 'A_SOURCE_FILE_RECEIVED'
      AND column_name = 'PROCESS_NAME';
    
    IF v_process_name_exists > 0 THEN
        DBMS_OUTPUT.PUT_LINE('INFO: Dropping column PROCESS_NAME...');
        EXECUTE IMMEDIATE 'ALTER TABLE CT_MRDS.A_SOURCE_FILE_RECEIVED DROP COLUMN PROCESS_NAME';
        DBMS_OUTPUT.PUT_LINE('SUCCESS: Column PROCESS_NAME dropped');
    ELSE
        DBMS_OUTPUT.PUT_LINE('INFO: Column PROCESS_NAME does not exist (already rolled back)');
    END IF;
    
    DBMS_OUTPUT.PUT_LINE('SUCCESS: A_SOURCE_FILE_RECEIVED table structure rollback completed');
    
EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('ERROR: Failed to rollback table structure: ' || SQLERRM);
        RAISE;
END;
/

PROMPT ====================================================================
PROMPT A_SOURCE_FILE_RECEIVED Table Rollback Completed
PROMPT ====================================================================
