-- ===================================================================
-- MARS-828: Archival Strategy Validation Trigger
-- ===================================================================
-- Purpose: Validates archival strategy configuration consistency
-- Author: Grzegorz Michalski
-- Date: 2026-01-27
-- Version: 1.0.0
-- ===================================================================

CREATE OR REPLACE TRIGGER CT_MRDS.TRG_BI_A_SRC_FILE_CFG_ARCH_VAL
BEFORE INSERT OR UPDATE ON CT_MRDS.A_SOURCE_FILE_CONFIG
FOR EACH ROW
DECLARE
    vErrorMsg VARCHAR2(1000);
BEGIN
    -- Validate MINIMUM_AGE_MONTHS required for specific strategies
    IF :NEW.ARCHIVAL_STRATEGY IN ('MINIMUM_AGE_MONTHS', 'HYBRID') 
       AND :NEW.MINIMUM_AGE_MONTHS IS NULL THEN
        vErrorMsg := 'MINIMUM_AGE_MONTHS is required for ' || :NEW.ARCHIVAL_STRATEGY || ' strategy';
        RAISE_APPLICATION_ERROR(-20999, vErrorMsg);
    END IF;
    
    -- Validate MINIMUM_AGE_MONTHS is non-negative (0 = current month only)
    IF :NEW.MINIMUM_AGE_MONTHS IS NOT NULL 
       AND :NEW.MINIMUM_AGE_MONTHS < 0 THEN
        RAISE_APPLICATION_ERROR(-20998, 'MINIMUM_AGE_MONTHS must be greater than or equal to 0');
    END IF;
    
    -- Warn if MINIMUM_AGE_MONTHS set but strategy doesn't use it
    IF :NEW.MINIMUM_AGE_MONTHS IS NOT NULL 
       AND :NEW.ARCHIVAL_STRATEGY NOT IN ('MINIMUM_AGE_MONTHS', 'HYBRID') THEN
        -- This is just a warning scenario - allow but could log
        NULL;
    END IF;
    
EXCEPTION
    WHEN OTHERS THEN
        RAISE;
END;
/
