-- ============================================================================
-- S89 (2026-06-25) — XÓA hết User TEST, chỉ giữ 17 User Solutions THẬT (+ admin)
-- Chỉ đạo: anh Kiệt FDC ("Xóa hết các User test ko liên quan, lấy User Solution thật vào").
--
-- Whitelist-keep (AN TOÀN): xóa MỌI User KHÔNG nằm trong 17 keep bên dưới.
-- Recon S89 (prod): 55 user -> KEEP 17 (admin + 16 real) -> DELETE 38:
--   - 3 active tên-giả: nv.cao, nv.test, nv.truong
--   - 34 đã-khóa: act.* bod.* ccm.tran equ.* fin.* hra.* nv.dinh pm.* pro.pham qs.*
--   - 1 typo domain: chuong.phan@solution.com.vn (anh chốt xóa — anh Chương dùng bản @solutions)
-- FK an toàn: KHÔNG user test nào là ApproverUserId (NO_ACTION không bị chặn — recon verified).
--   5 bảng con CASCADE tự xóa: EmployeeProfiles, UserRoles, UserClaims, UserLogins, UserTokens.
--   nv.test còn 1 PE (DrafterUserId loose-Guid, KHÔNG FK) -> xóa kèm (cascade child, proven S85).
-- Safety: SET XACT_ABORT ON (lỗi -> rollback toàn bộ) + BACKUP bước 0 (-b abort nếu backup fail)
--   + count-guard [30,45] (kỳ vọng 38) -> chặn nếu delete-set bất thường.
-- Run:  scp scripts/s89-delete-test-users.sql vietreport-vps:C:/temp/s89.sql
--       ssh vietreport-vps "sqlcmd -S .\SQLEXPRESS -d SolutionErp -i C:\temp\s89.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 -> backup fail thì abort TRƯỚC delete) =====
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_S89_preuserdelete.bak';
PRINT 'Backup device -> ' + @bkfile;
BACKUP DATABASE [SolutionErp] TO DISK = @bkfile WITH INIT, CHECKSUM, NAME = N'SolutionErp-S89-pre-user-delete';
GO

-- ===== 1. Keep-list 17 (admin + 16 user Solutions thật) =====
DECLARE @keep TABLE (Email nvarchar(256) PRIMARY KEY);
INSERT INTO @keep (Email) VALUES
 (N'admin@solutions.com.vn'),         (N'anh.nguyen@solutions.com.vn'),    (N'binh.le@solutions.com.vn'),
 (N'binh.lethanh@solutions.com.vn'),  (N'catalog.manager@solutions.com.vn'),(N'chuong.phan@solutions.com.vn'),
 (N'duy.nguyen@solutions.com.vn'),    (N'long.chau@solutions.com.vn'),     (N'long.nguyen@solutions.com.vn'),
 (N'luu.tran@solutions.com.vn'),      (N'nguyen.ho@solutions.com.vn'),     (N'phuong.nguyen@solutions.com.vn'),
 (N'thanh.lethanh@solutions.com.vn'), (N'tra.bui@solutions.com.vn'),       (N'tring.le@solutions.com.vn'),
 (N'truong.le@solutions.com.vn'),     (N'truong.nguyen@solutions.com.vn');

DECLARE @del TABLE (Id uniqueidentifier PRIMARY KEY, Email nvarchar(256));
INSERT INTO @del (Id, Email)
    SELECT Id, Email FROM Users WHERE Email NOT IN (SELECT Email FROM @keep);

PRINT '=== USERS TO DELETE ===';
SELECT Email FROM @del ORDER BY Email;
DECLARE @cnt int = (SELECT COUNT(*) FROM @del);
PRINT 'Count to delete = ' + CAST(@cnt AS varchar(10)) + ' (expect 38)';

-- Count-guard: chặn nếu delete-set rơi ngoài khoảng an toàn (vd keep-list sai -> xóa nhầm user thật)
IF @cnt < 30 OR @cnt > 45
BEGIN
    RAISERROR('S89 ABORT — delete count %d ngoai khoang an toan [30,45]. KHONG xoa.', 16, 1, @cnt);
    RETURN;
END

-- ===== 2. Thực thi xóa (transaction, XACT_ABORT bao ve) =====
BEGIN TRANSACTION;

  -- 2a. PE test của user bị xóa (chỉ nv.test có 1 PE — DrafterUserId loose-Guid, cascade child khi DELETE PE)
  DELETE FROM PurchaseEvaluations WHERE DrafterUserId IN (SELECT Id FROM @del);
  PRINT '  Test PE deleted           : ' + CAST(@@ROWCOUNT AS varchar(10));

  -- 2b. Xóa user (CASCADE: EmployeeProfiles / UserRoles / UserClaims / UserLogins / UserTokens)
  DELETE FROM Users WHERE Id IN (SELECT Id FROM @del);
  PRINT '  Users deleted             : ' + CAST(@@ROWCOUNT AS varchar(10));

COMMIT TRANSACTION;
PRINT 'S89 delete COMMITTED.';

-- ===== 3. Verify AFTER (kỳ vọng còn đúng 17 user thật) =====
PRINT '=== AFTER — remaining users (expect 17) ===';
SELECT Email FROM Users ORDER BY Email;
SELECT COUNT(*) AS RemainingUsers FROM Users;
GO
