-- ===================================================================
-- MARS-956 Rollback Step 2: Clean Process Logs
-- ===================================================================
-- Purpose: Remove MARS-956 process logs from A_PROCESS_LOG
-- Author: Grzegorz Michalski
-- Date: 2026-02-12

SET SERVEROUTPUT ON SIZE UNLIMITED
SET TIMING ON

PROMPT =========================================================================
PROMPT MARS-956 Rollback Step 2: Clean Process Logs
PROMPT =========================================================================

DECLARE
    vLogCount NUMBER := 0;
    vDeletedCount NUMBER := 0;
    vErrorMsg VARCHAR2(4000);
BEGIN
    -- Count logs to be deleted
    SELECT COUNT(*)
    INTO vLogCount
    FROM CT_MRDS.A_PROCESS_LOG
    WHERE PROCESS_NAME IN ('MARS-956', 'MARS-956-ROLLBACK')
      AND LOG_TIMESTAMP >= SYSDATE - 7;  -- Last week (safety)
    
    DBMS_OUTPUT.PUT_LINE('Process log entries to be deleted: ' || vLogCount);
    
    IF vLogCount > 0 THEN
        -- Show recent logs before deletion
        DBMS_OUTPUT.PUT_LINE('Recent MARS-956 log entries being removed:');
        FOR rec IN (
            SELECT A_PROCESS_LOG_KEY,
                   TO_CHAR(LOG_TIMESTAMP, 'YYYY-MM-DD HH24:MI:SS') AS LOG_TIME,
                   PROCEDURE_NAME,
                   LOG_LEVEL,
                   SUBSTR(LOG_MESSAGE, 1, 40) AS MESSAGE
            FROM CT_MRDS.A_PROCESS_LOG
            WHERE PROCESS_NAME IN ('MARS-956', 'MARS-956-ROLLBACK')
              AND LOG_TIMESTAMP >= SYSDATE - 7
            ORDER BY LOG_TIMESTAMP DESC
            FETCH FIRST 10 ROWS ONLY
        ) LOOP
            DBMS_OUTPUT.PUT_LINE('- ' || rec.LOG_TIME || ' [' || rec.LOG_LEVEL || '] ' || 
                               rec.PROCEDURE_NAME || ': ' || rec.MESSAGE);
        END LOOP;
        
        -- Delete the process logs
        DELETE FROM CT_MRDS.A_PROCESS_LOG
        WHERE PROCESS_NAME IN ('MARS-956', 'MARS-956-ROLLBACK')
          AND LOG_TIMESTAMP >= SYSDATE - 7;
        
        vDeletedCount := SQL%ROWCOUNT;
        COMMIT;
        
        DBMS_OUTPUT.PUT_LINE('SUCCESS: Successfully deleted ' || vDeletedCount || ' process log entries');
        
    ELSE
        DBMS_OUTPUT.PUT_LINE('SUCCESS: No process log entries found to delete');
    END IF;

EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
        vErrorMsg := 'Failed to clean process logs: ' || SQLERRM;
        DBMS_OUTPUT.PUT_LINE('ERROR: Error during process log cleanup: ' || SQLERRM);
        -- Log the error (will remain after rollback for debugging)
        INSERT INTO CT_MRDS.A_PROCESS_LOG (PROCESS_NAME, PROCEDURE_NAME, LOG_LEVEL, LOG_MESSAGE)
        VALUES ('MARS-956-ROLLBACK', 'CLEANUP_PROCESS_LOGS', 'ERROR', vErrorMsg);
        COMMIT;
        RAISE;
END;
/

PROMPT =========================================================================
PROMPT Process Log Cleanup Completed
PROMPT =========================================================================