-- Plan T5 S23 t10 (2026-05-15) — Final cleanup sau khi DemoSeed:Disabled deploy
-- Bro request: "các cái demo quy trình cũ -> xóa hết luôn đi nhé"
-- State trước T5: 4 PE + 2 V1 + 1 V2 (re-seeded sau Plan R+S do DbInitializer)
-- Backup rollback: C:\Backup\SolutionErp_pre_cleanup_2026-05-15.bak (Plan R, 18.5MB)
-- Sau T5 + Plan T flag active: re-seed KHÔNG còn → permanent clean slate

USE SolutionErp;
GO

SET QUOTED_IDENTIFIER ON;
SET ANSI_NULLS ON;
GO

PRINT '=== Plan T5 — Final cleanup ALL workflow + PE START ===';
PRINT 'Pre-state:';
SELECT 'PE total' AS Entity, COUNT(*) AS Cnt FROM PurchaseEvaluations
UNION ALL SELECT 'V2 workflows', COUNT(*) FROM ApprovalWorkflows
UNION ALL SELECT 'V1 workflows', COUNT(*) FROM PurchaseEvaluationWorkflowDefinitions
UNION ALL SELECT 'Contracts', COUNT(*) FROM Contracts;

PRINT '';
PRINT '=== Step 1: DELETE ALL PE (cascade child) ===';
BEGIN TRY
    BEGIN TRANSACTION DeleteAllPE;
    DELETE FROM PurchaseEvaluations;
    DECLARE @PeCnt INT = @@ROWCOUNT;
    PRINT 'PE deleted: ' + CAST(@PeCnt AS NVARCHAR(10));
    COMMIT TRANSACTION DeleteAllPE;
    PRINT 'PE COMMIT OK';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION DeleteAllPE;
    PRINT 'PE FAILED: ' + ERROR_MESSAGE();
    THROW;
END CATCH;

PRINT '';
PRINT '=== Step 2: DELETE ALL V2 workflows (cascade Steps + Levels) ===';
BEGIN TRY
    BEGIN TRANSACTION DeleteAllV2;
    DELETE FROM ApprovalWorkflows;
    DECLARE @V2Cnt INT = @@ROWCOUNT;
    PRINT 'V2 deleted: ' + CAST(@V2Cnt AS NVARCHAR(10));
    COMMIT TRANSACTION DeleteAllV2;
    PRINT 'V2 COMMIT OK';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION DeleteAllV2;
    PRINT 'V2 FAILED: ' + ERROR_MESSAGE();
    THROW;
END CATCH;

PRINT '';
PRINT '=== Step 3: DELETE ALL V1 workflows (cascade Steps + Approvers) ===';
BEGIN TRY
    BEGIN TRANSACTION DeleteAllV1;
    DELETE FROM PurchaseEvaluationWorkflowDefinitions;
    DECLARE @V1Cnt INT = @@ROWCOUNT;
    PRINT 'V1 deleted: ' + CAST(@V1Cnt AS NVARCHAR(10));
    COMMIT TRANSACTION DeleteAllV1;
    PRINT 'V1 COMMIT OK';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION DeleteAllV1;
    PRINT 'V1 FAILED: ' + ERROR_MESSAGE();
    THROW;
END CATCH;

-- Bro chưa request xóa Contract — KHÔNG đụng Contracts table (incl [DEMO] HĐ).
-- Nếu bro want cleanup Contract sau → spawn Plan U riêng.

PRINT '';
PRINT '=== Post-state (expect PE=0 / V2=0 / V1=0) ===';
SELECT 'PE total' AS Entity, COUNT(*) AS Cnt FROM PurchaseEvaluations
UNION ALL SELECT 'V2 workflows', COUNT(*) FROM ApprovalWorkflows
UNION ALL SELECT 'V1 workflows', COUNT(*) FROM PurchaseEvaluationWorkflowDefinitions
UNION ALL SELECT 'V2 Steps cascade', COUNT(*) FROM ApprovalWorkflowSteps
UNION ALL SELECT 'V2 Levels cascade', COUNT(*) FROM ApprovalWorkflowLevels
UNION ALL SELECT 'V1 Steps cascade', COUNT(*) FROM PurchaseEvaluationWorkflowSteps;

PRINT '=== Plan T5 complete — UAT permanent clean slate ===';
