-- MARS-828 ROLLBACK: Remove TRASH retention statuses from A_SOURCE_FILE_RECEIVED
-- Author: Grzegorz Michalski
-- Date: 2026-02-09
-- Description: Rollback TRASH retention statuses to original constraint

PROMPT ========================================
PROMPT MARS-828 ROLLBACK: Removing TRASH retention statuses
PROMPT ========================================

-- Check if any files have new statuses
DECLARE
    vTrashCount NUMBER;
    vPurgedCount NUMBER;
BEGIN
    SELECT COUNT(*) INTO vTrashCount
    FROM CT_MRDS.A_SOURCE_FILE_RECEIVED
    WHERE PROCESSING_STATUS = 'ARCHIVED_AND_TRASHED';
    
    SELECT COUNT(*) INTO vPurgedCount
    FROM CT_MRDS.A_SOURCE_FILE_RECEIVED
    WHERE PROCESSING_STATUS = 'ARCHIVED_AND_PURGED';
    
    DBMS_OUTPUT.PUT_LINE('Files with ARCHIVED_AND_TRASHED status: ' || vTrashCount);
    DBMS_OUTPUT.PUT_LINE('Files with ARCHIVED_AND_PURGED status: ' || vPurgedCount);
    
    IF vTrashCount > 0 OR vPurgedCount > 0 THEN
        DBMS_OUTPUT.PUT_LINE('');
        DBMS_OUTPUT.PUT_LINE('WARNING: Files exist with new statuses!');
        DBMS_OUTPUT.PUT_LINE('Migrating statuses to ARCHIVED before rollback...');
        
        -- Migrate new statuses back to ARCHIVED
        UPDATE CT_MRDS.A_SOURCE_FILE_RECEIVED
        SET PROCESSING_STATUS = 'ARCHIVED'
        WHERE PROCESSING_STATUS IN ('ARCHIVED_AND_TRASHED', 'ARCHIVED_AND_PURGED');
        
        COMMIT;
        DBMS_OUTPUT.PUT_LINE('Migrated ' || SQL%ROWCOUNT || ' records to ARCHIVED status');
    ELSE
        DBMS_OUTPUT.PUT_LINE('No files with new statuses - safe to rollback');
    END IF;
END;
/

-- Drop new constraint
ALTER TABLE CT_MRDS.A_SOURCE_FILE_RECEIVED DROP CONSTRAINT A_SOURCE_FILE_RECEIVED_CHK;

-- Restore original constraint
ALTER TABLE CT_MRDS.A_SOURCE_FILE_RECEIVED ADD CONSTRAINT A_SOURCE_FILE_RECEIVED_CHK 
    CHECK (PROCESSING_STATUS IN (
        'RECEIVED', 
        'VALIDATED',
        'VALIDATION_FAILED',
        'READY_FOR_INGESTION', 
        'INGESTED', 
        'ARCHIVED'
    ));

-- Remove comment
COMMENT ON COLUMN CT_MRDS.A_SOURCE_FILE_RECEIVED.PROCESSING_STATUS IS 
    'File processing status: RECEIVED → VALIDATED → READY_FOR_INGESTION → INGESTED → ARCHIVED';

-- Verify constraint restored
SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'A_SOURCE_FILE_RECEIVED'
  AND constraint_name = 'A_SOURCE_FILE_RECEIVED_CHK';

-- Show current status distribution
SELECT PROCESSING_STATUS, COUNT(*) as FILE_COUNT
FROM CT_MRDS.A_SOURCE_FILE_RECEIVED
GROUP BY PROCESSING_STATUS
ORDER BY PROCESSING_STATUS;

PROMPT ========================================
PROMPT TRASH retention statuses rollback completed
PROMPT Original constraint restored
PROMPT All ARCHIVED_AND_TRASHED/ARCHIVED_AND_PURGED migrated to ARCHIVED
PROMPT ========================================
