-- ============================================================================
-- MARS-1409-POSTHOOK Master Installation Script
-- ============================================================================
-- Purpose: Post-hook for MARS-1409 - Backfill A_WORKFLOW_HISTORY_KEY for
--          existing A_SOURCE_FILE_RECEIVED records by joining with ODS tables.
-- Author: Grzegorz Michalski
-- Date: 2026-03-13
-- Prerequisites: MARS-1409 must be installed first (column must exist)
-- ============================================================================

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/INSTALL_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 Installation Starting
PROMPT ============================================================================
PROMPT Purpose: Backfill A_WORKFLOW_HISTORY_KEY for historical records
PROMPT          in A_SOURCE_FILE_RECEIVED using matching ODS tables.
PROMPT
PROMPT This script will:
PROMPT - Update A_WORKFLOW_HISTORY_KEY for records with targeted PROCESSING_STATUS
PROMPT - Match records by SOURCE_FILE_NAME against file$name in ODS tables
PROMPT - Skip configs with no NULL records or missing ODS tables
PROMPT
PROMPT Prerequisite: MARS-1409 installed (A_WORKFLOW_HISTORY_KEY column exists)
PROMPT Expected Duration: 30-180 minutes (depends on data volume)
PROMPT ============================================================================

-- Confirm installation with user
ACCEPT continue CHAR PROMPT 'Type YES to continue with installation, 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, 'Installation aborted by user');
    END IF;
END;
/
WHENEVER SQLERROR CONTINUE

PROMPT
PROMPT ============================================================================
PROMPT PREREQUISITE CHECK: Verifying MARS-1409 objects
PROMPT ============================================================================
WHENEVER SQLERROR EXIT SQL.SQLCODE
DECLARE
        vColCount NUMBER;
        vTableCount NUMBER;
BEGIN
        SELECT COUNT(*)
            INTO vColCount
            FROM ALL_TAB_COLUMNS
         WHERE OWNER = 'CT_MRDS'
             AND TABLE_NAME = 'A_SOURCE_FILE_RECEIVED'
             AND COLUMN_NAME = 'A_WORKFLOW_HISTORY_KEY';

        IF vColCount = 0 THEN
                RAISE_APPLICATION_ERROR(-20001,
                        'Prerequisite failed: CT_MRDS.A_SOURCE_FILE_RECEIVED.A_WORKFLOW_HISTORY_KEY not found. Install MARS-1409 first (or do not run POSTHOOK after rollback).');
        END IF;

        SELECT COUNT(*)
            INTO vTableCount
            FROM ALL_TABLES
         WHERE OWNER = 'CT_MRDS'
             AND TABLE_NAME = 'A_WORKFLOW_HISTORY';

        IF vTableCount = 0 THEN
                RAISE_APPLICATION_ERROR(-20002,
                        'Prerequisite failed: CT_MRDS.A_WORKFLOW_HISTORY table not found.');
        END IF;

        DBMS_OUTPUT.PUT_LINE('OK: Prerequisites satisfied (MARS-1409 schema changes detected).');
END;
/
WHENEVER SQLERROR CONTINUE

PROMPT
PROMPT ============================================================================
PROMPT STEP 1: Backfill A_WORKFLOW_HISTORY_KEY for existing records
PROMPT ============================================================================
@@01_MARS_1409_POSTHOOK_update_existing_workflow_keys.sql

PROMPT
PROMPT ============================================================================
PROMPT STEP 2: Diagnose workflow key status
PROMPT ============================================================================
@@02_MARS_1409_POSTHOOK_diagnose_workflow_key_status.sql

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

spool off

quit;
