-- =================================================================
-- Clean transactional data cho UAT V2 schema (Mig 22-24, Session 17)
-- =================================================================
-- Xóa:    PE / Contract / Budget + tất cả con cháu + Notifications + CodeSequences
-- Giữ:    Master data (Users, Suppliers, Projects, Departments, MaterialItems,
--         ServiceItems, WorkItems, UnitsOfMeasure, MenuItems, Permissions, Roles)
--         + Workflow config (V1 PurchaseEvaluationWorkflowDefinitions, WorkflowDefinitions
--           legacy + V2 ApprovalWorkflows/Steps/Levels) + ContractTemplates/Clauses
--
-- USAGE:
--   Local Dev:   sqlcmd -S "(localdb)\MSSQLLocalDB" -d SolutionErp_Dev -i scripts\sql\clean-transactional-uat.sql
--   Prod (VPS):  paste vào SSMS hoặc sqlcmd connect prod DB
--
-- ⚠ DESTRUCTIVE — backup trước nếu data còn cần.
-- =================================================================

-- Required cho filtered indexes (Mig 19/20) — sqlcmd default off
SET QUOTED_IDENTIFIER ON;
SET ANSI_NULLS ON;
SET NOCOUNT ON;
PRINT '====================================================';
PRINT 'Clean transactional data START at ' + CONVERT(varchar, GETUTCDATE(), 120) + ' UTC';
PRINT '====================================================';

BEGIN TRANSACTION;

-- ===== 1. PE module — child rows trước (FK Cascade chain) =====
DELETE FROM dbo.PurchaseEvaluationDepartmentApprovals;
PRINT '  PE.DepartmentApprovals    : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';
DELETE FROM dbo.PurchaseEvaluationDepartmentOpinions;
PRINT '  PE.DepartmentOpinions     : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';
DELETE FROM dbo.PurchaseEvaluationAttachments;
PRINT '  PE.Attachments            : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';
DELETE FROM dbo.PurchaseEvaluationChangelogs;
PRINT '  PE.Changelogs             : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';
DELETE FROM dbo.PurchaseEvaluationApprovals;
PRINT '  PE.Approvals              : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';
DELETE FROM dbo.PurchaseEvaluationQuotes;
PRINT '  PE.Quotes                 : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';
DELETE FROM dbo.PurchaseEvaluationDetails;
PRINT '  PE.Details                : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';
DELETE FROM dbo.PurchaseEvaluationSuppliers;
PRINT '  PE.Suppliers              : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';

-- ===== 2. PE main (giải phóng FK PE.ContractId + PE.BudgetId trước) =====
DELETE FROM dbo.PurchaseEvaluations;
PRINT '  PurchaseEvaluations       : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';

-- ===== 3. Contract per-type Details =====
DELETE FROM dbo.ThauPhuDetails;
DELETE FROM dbo.GiaoKhoanDetails;
DELETE FROM dbo.NhaCungCapDetails;
DELETE FROM dbo.DichVuDetails;
DELETE FROM dbo.MuaBanDetails;
DELETE FROM dbo.NguyenTacNccDetails;
DELETE FROM dbo.NguyenTacDvDetails;
PRINT '  Contract per-type Details : cleaned';

-- ===== 4. Contract child rows =====
DELETE FROM dbo.ContractDepartmentApprovals;
DELETE FROM dbo.ContractAttachments;
DELETE FROM dbo.ContractComments;
DELETE FROM dbo.ContractChangelogs;
DELETE FROM dbo.ContractApprovals;
PRINT '  Contract child rows       : cleaned';

-- ===== 5. Contract main =====
DELETE FROM dbo.Contracts;
PRINT '  Contracts                 : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';

-- ===== 6. Budget module (PE+Contract đã giải phóng FK BudgetId) =====
DELETE FROM dbo.BudgetDepartmentApprovals;
DELETE FROM dbo.BudgetChangelogs;
DELETE FROM dbo.BudgetApprovals;
DELETE FROM dbo.BudgetDetails;
DELETE FROM dbo.Budgets;
PRINT '  Budgets + children        : cleaned';

-- ===== 7. Code sequences (reset count) =====
DELETE FROM dbo.PurchaseEvaluationCodeSequences;
DELETE FROM dbo.ContractCodeSequences;
PRINT '  Code sequences            : reset';

-- ===== 8. Notifications (dangling refs sau khi xóa phiếu) =====
DELETE FROM dbo.Notifications;
PRINT '  Notifications             : ' + CAST(@@ROWCOUNT as varchar) + ' rows deleted';

COMMIT TRANSACTION;

PRINT '';
PRINT '====================================================';
PRINT 'Clean transactional data DONE at ' + CONVERT(varchar, GETUTCDATE(), 120) + ' UTC';
PRINT '====================================================';
PRINT '';
PRINT '===== Master KEEP verify =====';

SELECT
    (SELECT COUNT(*) FROM dbo.Users)              AS Users,
    (SELECT COUNT(*) FROM dbo.Suppliers)           AS Suppliers,
    (SELECT COUNT(*) FROM dbo.Projects)            AS Projects,
    (SELECT COUNT(*) FROM dbo.Departments)         AS Departments,
    (SELECT COUNT(*) FROM dbo.MaterialItems)       AS Materials,
    (SELECT COUNT(*) FROM dbo.ServiceItems)        AS Services,
    (SELECT COUNT(*) FROM dbo.WorkItems)           AS WorkItems,
    (SELECT COUNT(*) FROM dbo.UnitsOfMeasure)      AS Units;

SELECT
    (SELECT COUNT(*) FROM dbo.ApprovalWorkflows)        AS Aw_V2,
    (SELECT COUNT(*) FROM dbo.ApprovalWorkflowSteps)    AS Aw_V2_Steps,
    (SELECT COUNT(*) FROM dbo.ApprovalWorkflowLevels)   AS Aw_V2_Levels,
    (SELECT COUNT(*) FROM dbo.WorkflowDefinitions)      AS Wf_V1_Legacy_HD,
    (SELECT COUNT(*) FROM dbo.PurchaseEvaluationWorkflowDefinitions) AS Wf_V1_Legacy_PE;

SELECT
    (SELECT COUNT(*) FROM dbo.PurchaseEvaluations)  AS PE_after_clean,
    (SELECT COUNT(*) FROM dbo.Contracts)             AS Contract_after_clean,
    (SELECT COUNT(*) FROM dbo.Budgets)               AS Budget_after_clean,
    (SELECT COUNT(*) FROM dbo.Notifications)         AS Notify_after_clean;
