-- ============================================================================
-- S85 (2026-06-23) — Wipe UAT testing data ("clear sạch") trước UAT anh Kiệt FDC sáng nay
-- Chỉ đạo: anh Kiệt FDC (Zalo "Clear sạch giúp anh nhé" + "Clear truoc em. Xong anh
--          check một sáng nay em"). Quy trình destructive-prod chuẩn S59:
--          recon -> AskUserQuestion chốt scope -> script committed -> chạy -> verify exact.
--
-- Anh chốt (AskUserQuestion S85):
--   - PeWorkItemBudgets (28) -> XÓA (UAT sạch hoàn toàn, ô ngân sách trống lại).
--   - Suppliers test thêm sau S59 -> XÓA 21 (CreatedAt >= 2026-06-11); GIỮ 22 gốc
--     (CreatedAt < 2026-06-11: 19 demo 04/21-23 + 3 real S55 06-09). Mốc cắt SẠCH
--     (06-10 trống — không nhập nhằng).
--
-- XÓA:  43 PurchaseEvaluations (cascade child ~700: Suppliers/Details/Quotes/Approvals/
--       Changelogs/Attachments/LevelOpinions/DeptOpinions) · 28 PeWorkItemBudgets
--       (loose-Guid per Dự-án×Hạng-mục — KHÔNG cascade theo PE -> DELETE riêng) · 1
--       Contract (cascade) · 32 Notifications · 21 Suppliers test (CreatedAt >= 06-11)
--       · PeSeq + CtSeq (reset -> generator INSERT lại LastSeq=1 -> phiếu thật đầu = .../001).
-- GIỮ:  22 Suppliers gốc · Projects 70 · WorkItems 71 · Users 55 · Permissions/MenuItems/
--       Roles · Workflows (7 active + Steps/Levels/Approvers — KHÔNG đụng config) ·
--       ContractTemplates 9 · HRM/Office master (EmployeeProfiles/MeetingRooms/Vehicles/
--       Drivers/LeaveTypes/Holidays/ShiftPatterns/OtPolicies) · EmployeeCodeSequences.
-- FK:   PE child ALL CASCADE (Quotes NO_ACTION dọn qua Details->Quotes, proven S59).
--       Suppliers xóa SAU PE+Contracts (đã giải phóng SelectedSupplierId/Quotes/Contract).
-- Safety: SET XACT_ABORT ON (lỗi -> rollback toàn bộ) + BACKUP bước 0 ngoài tran +
--         chạy sqlcmd -b (backup fail -> abort TRƯỚC wipe). Resurrect-safe: DemoSeed:Disabled.
-- Run:  scp -> VPS C:\temp\s85.sql ; sqlcmd -S .\SQLEXPRESS -d SolutionErp -i C:\temp\s85.sql -f 65001 -b
-- ============================================================================
SET QUOTED_IDENTIFIER ON;
SET ANSI_NULLS ON;
SET NOCOUNT ON;
SET XACT_ABORT ON;
GO

-- ===== 0. BACKUP insurance (NGOÀI transaction; -b -> fail thì abort trước wipe) =====
-- Lấy backup dir từ registry (SQL service account chắc chắn ghi được; D:\ KHÔNG tồn tại
-- trên VPS này — chỉ ổ C:). xp_instance_regread auto-resolve path theo instance.
DECLARE @bkdir nvarchar(512), @bkfile nvarchar(600);
EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @bkdir OUTPUT;
SET @bkfile = @bkdir + N'\SolutionErp_S85_prewipe.bak';
PRINT 'Backup device -> ' + @bkfile;
BACKUP DATABASE [SolutionErp] TO DISK = @bkfile WITH INIT, CHECKSUM, NAME = N'SolutionErp-S85-pre-wipe';
GO

PRINT '=== BEFORE ===';
SELECT 'PE' AS T, COUNT(*) AS C FROM PurchaseEvaluations
UNION ALL SELECT 'PeWorkItemBudgets', COUNT(*) FROM PeWorkItemBudgets
UNION ALL SELECT 'Contracts', COUNT(*) FROM Contracts
UNION ALL SELECT 'Notifications', COUNT(*) FROM Notifications
UNION ALL SELECT 'Suppliers_total', COUNT(*) FROM Suppliers
UNION ALL SELECT 'Suppliers_test(>=06-11)', COUNT(*) FROM Suppliers WHERE CreatedAt >= '2026-06-11'
UNION ALL SELECT 'PeSeq', COUNT(*) FROM PurchaseEvaluationCodeSequences
UNION ALL SELECT 'CtSeq', COUNT(*) FROM ContractCodeSequences;
GO

BEGIN TRANSACTION;

-- 1. Phiếu PE (cascade child)
DELETE FROM PurchaseEvaluations;
PRINT '  PurchaseEvaluations deleted : ' + CAST(@@ROWCOUNT AS varchar);

-- 2. Ngân sách per-gói-thầu (loose-Guid, KHÔNG cascade theo PE)
DELETE FROM PeWorkItemBudgets;
PRINT '  PeWorkItemBudgets deleted   : ' + CAST(@@ROWCOUNT AS varchar);

-- 3. Hợp đồng (cascade child)
DELETE FROM Contracts;
PRINT '  Contracts deleted           : ' + CAST(@@ROWCOUNT AS varchar);

-- 4. Thông báo
DELETE FROM Notifications;
PRINT '  Notifications deleted       : ' + CAST(@@ROWCOUNT AS varchar);

-- 5. NCC test thêm sau S59 (giữ 22 gốc CreatedAt < 2026-06-11)
DELETE FROM Suppliers WHERE CreatedAt >= '2026-06-11';
PRINT '  Suppliers test deleted      : ' + CAST(@@ROWCOUNT AS varchar);

-- 6. Reset bộ đếm mã (DELETE row -> generator INSERT lại LastSeq=1 -> .../001)
DELETE FROM PurchaseEvaluationCodeSequences;
DELETE FROM ContractCodeSequences;
PRINT '  Code sequences reset (Pe+Ct)';

PRINT '=== AFTER (expect transactional=0, Suppliers=22, master giữ) ===';
SELECT 'PE' AS T, COUNT(*) AS C FROM PurchaseEvaluations
UNION ALL SELECT 'PeWorkItemBudgets', COUNT(*) FROM PeWorkItemBudgets
UNION ALL SELECT 'PeSuppliers', COUNT(*) FROM PurchaseEvaluationSuppliers
UNION ALL SELECT 'PeQuotes', COUNT(*) FROM PurchaseEvaluationQuotes
UNION ALL SELECT 'PeAttachments', COUNT(*) FROM PurchaseEvaluationAttachments
UNION ALL SELECT 'PeChangelogs', COUNT(*) FROM PurchaseEvaluationChangelogs
UNION ALL SELECT 'Contracts', COUNT(*) FROM Contracts
UNION ALL SELECT 'Notifications', COUNT(*) FROM Notifications
UNION ALL SELECT 'Suppliers_keep', COUNT(*) FROM Suppliers
UNION ALL SELECT 'PeSeq', COUNT(*) FROM PurchaseEvaluationCodeSequences
UNION ALL SELECT 'CtSeq', COUNT(*) FROM ContractCodeSequences
UNION ALL SELECT 'KEEP_Projects', COUNT(*) FROM Projects
UNION ALL SELECT 'KEEP_WorkItems', COUNT(*) FROM WorkItems
UNION ALL SELECT 'KEEP_Users', COUNT(*) FROM Users
UNION ALL SELECT 'KEEP_Workflows', COUNT(*) FROM ApprovalWorkflows
UNION ALL SELECT 'KEEP_Templates', COUNT(*) FROM ContractTemplates;

COMMIT TRANSACTION;
PRINT 'S85 wipe COMMITTED.';
GO
