-- ====================================================================
-- MARS-835-PREHOOK: Update A_SOURCE_FILE_RECEIVED Table Structure
-- ====================================================================
-- Purpose: 
--   1. Rename column ARCH_FILE_NAME to ARCH_PATH
--   2. Add new column PROCESS_NAME VARCHAR2(200)
-- Author: Grzegorz Michalski
-- Date: 2026-02-13
-- ====================================================================

SET SERVEROUTPUT ON SIZE UNLIMITED
SET TIMING ON

PROMPT ====================================================================
PROMPT MARS-835-PREHOOK: Updating A_SOURCE_FILE_RECEIVED table structure
PROMPT ====================================================================

-- Check if column ARCH_FILE_NAME exists
DECLARE
    v_column_exists NUMBER;
    v_process_name_exists NUMBER;
BEGIN
    -- Check if ARCH_FILE_NAME exists
    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_FILE_NAME';
    
    IF v_column_exists > 0 THEN
        DBMS_OUTPUT.PUT_LINE('INFO: Renaming column ARCH_FILE_NAME to ARCH_PATH...');
        EXECUTE IMMEDIATE 'ALTER TABLE CT_MRDS.A_SOURCE_FILE_RECEIVED RENAME COLUMN ARCH_FILE_NAME TO ARCH_PATH';
        DBMS_OUTPUT.PUT_LINE('SUCCESS: Column renamed to ARCH_PATH');
    ELSE
        DBMS_OUTPUT.PUT_LINE('INFO: Column ARCH_FILE_NAME does not exist (already renamed or first install)');
    END IF;
    
    -- Check if PROCESS_NAME already exists
    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: Adding new column PROCESS_NAME...');
        EXECUTE IMMEDIATE 'ALTER TABLE CT_MRDS.A_SOURCE_FILE_RECEIVED ADD (PROCESS_NAME VARCHAR2(200))';
        DBMS_OUTPUT.PUT_LINE('SUCCESS: Column PROCESS_NAME added');
        
        -- Add comment on new column
        EXECUTE IMMEDIATE 'COMMENT ON COLUMN CT_MRDS.A_SOURCE_FILE_RECEIVED.PROCESS_NAME IS ''Name of the process that created this record''';
        DBMS_OUTPUT.PUT_LINE('SUCCESS: Comment added to PROCESS_NAME column');
    ELSE
        DBMS_OUTPUT.PUT_LINE('INFO: Column PROCESS_NAME already exists');
    END IF;
    
    DBMS_OUTPUT.PUT_LINE('SUCCESS: A_SOURCE_FILE_RECEIVED table structure updated successfully');
    
EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('ERROR: Failed to update table structure: ' || SQLERRM);
        RAISE;
END;
/

PROMPT ====================================================================
PROMPT A_SOURCE_FILE_RECEIVED Table Update Completed
PROMPT ====================================================================
