-- ====================================================================
-- TRG_A_WORKFLOW_HISTORY Trigger Definition
-- ====================================================================
-- Purpose: Trigger to:
--          1. Insert workflow completion data to CT_ODS.A_LOAD_HISTORY
--          2. MARS-1409: Mark linked A_SOURCE_FILE_RECEIVED records as INGESTED
-- ====================================================================

CREATE OR REPLACE EDITIONABLE TRIGGER "CT_MRDS"."TRG_A_WORKFLOW_HISTORY" 
AFTER INSERT OR UPDATE OF workflow_successful ON CT_MRDS.A_WORKFLOW_HISTORY 
REFERENCING NEW AS new OLD AS old
FOR EACH ROW
DECLARE
  v_workflow_name VARCHAR2(128);
  v_wla_id NUMBER;
BEGIN
  -- Original logic: Insert into CT_ODS.A_LOAD_HISTORY for specific ODS workflows
  IF :new.workflow_name IN ('w_ODS_LM_STANDING_FACILITIES', 'w_ODS_CSDB_DEBT', 'w_ODS_CSDB_DEBT_DAILY', 'w_ODS_CSDB_RATINGS_FULL') AND :new.service_name = 'ODS' THEN
    IF :new.workflow_successful <> :old.workflow_successful AND :new.workflow_successful = 'Y'   THEN 
      IF :new.workflow_name = 'w_ODS_LM_STANDING_FACILITIES' THEN
        v_workflow_name := 'w_ODS_LM_STANDING_FACILITY';
      ELSE
        v_workflow_name := :new.workflow_name;  
      END IF;
      BEGIN
        v_wla_id := TO_NUMBER(:new.orchestration_run_id);
      EXCEPTION 
        WHEN OTHERS THEN 
          NULL;
      END;
      INSERT INTO CT_ODS.A_LOAD_HISTORY (
        a_etl_load_set_key, workflow_name, infa_run_id, load_start, load_end, 
        exdi_appl_req_id, exdi_correlation_id, load_successful, wla_run_id, dq_flag
      ) VALUES (
        :new.a_workflow_history_key, v_workflow_name, NULL, :new.workflow_start, :new.workflow_end, 
        NULL, NULL, :new.workflow_successful, v_wla_id, 'F'
      );
    END IF;
  END IF;

  -- MARS-1409: When workflow completes successfully, mark linked files as INGESTED
  IF :new.workflow_successful = 'Y' THEN
    IF INSERTING OR (UPDATING AND (:old.workflow_successful IS NULL OR :old.workflow_successful != 'Y')) THEN
      UPDATE CT_MRDS.A_SOURCE_FILE_RECEIVED
      SET    PROCESSING_STATUS = 'INGESTED',
             PROCESS_NAME      = :new.service_name
      WHERE  A_WORKFLOW_HISTORY_KEY = :new.a_workflow_history_key;
    END IF;
  END IF;
END;

/