-- Plan S S23 t9 (2026-05-15) — Wipe ALL workflows (UAT clean slate hoàn toàn)
-- Bro request: "các cái demo quy trình cũ -> xóa hết luôn đi nhé"
-- Current state post-Plan R: 2 V2 ghim + 2 V1 active (đều seed demo cumulative)
-- Backup rollback: C:\Backup\SolutionErp_pre_cleanup_2026-05-15.bak (Plan R)
-- Hậu quả: user KHÔNG tạo được phiếu mới (Workspace Select empty) cho đến khi
-- admin Designer seed workflow mới from scratch.

USE SolutionErp;
GO

SET QUOTED_IDENTIFIER ON;
SET ANSI_NULLS ON;
GO

PRINT '=== Plan S — Wipe ALL workflows START ===';
PRINT 'Pre-state:';
SELECT 'V2 workflows' AS Entity, COUNT(*) AS Cnt FROM ApprovalWorkflows
UNION ALL SELECT 'V1 workflows', COUNT(*) FROM PurchaseEvaluationWorkflowDefinitions;

PRINT '';
PRINT '=== Step 1: DELETE ALL V2 ApprovalWorkflows (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 — rollback. Error: ' + ERROR_MESSAGE();
    THROW;
END CATCH;

PRINT '';
PRINT '=== Step 2: DELETE ALL V1 PurchaseEvaluationWorkflowDefinitions (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 — rollback. Error: ' + ERROR_MESSAGE();
    THROW;
END CATCH;

PRINT '';
PRINT '=== Post-state (expect 0/0) ===';
SELECT 'V2 workflows' AS Entity, COUNT(*) AS Cnt 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
UNION ALL SELECT 'V1 Approvers (cascade)', COUNT(*) FROM PurchaseEvaluationWorkflowStepApprovers;

PRINT '=== Plan S complete ===';
