/*
  Fix users wrongly marked DayaLoan who were manually charged (RefId LIKE 'manualy%').

  Scope: ONLY users linked to manualy transactions — NOT the full 47-user WrongDaya list.
         Real Daya users (RefId LIKE 'C4%') are excluded automatically.

  Actions:
    - PurchaseMethod 1→3 on Users / Club / Cycle / UPP
    - Clear HasReceivedDayaCredit / DayaCreditReceivedAt
    - Soft-delete stub DayaLoanContracts (unprocessed, no Tx)
    - Fix broken WH.RefrenceId where CreatedBy hint points to existing manualy Tx
    - Create missing UPP Manual(3) reusing existing manualy Tx (never create new Tx)
    - Create missing WH rows only when Tx exists but no WH links to it (history-only, no charge)

  RefrenceId=0 rule:
    Tx is resolved ONLY via numeric CreatedBy hint when that Tx exists with RefId manualy%.
    Mobile-only or manualy{N} suffix alone is NOT used to assume a Tx exists.

  PackagePurchaseMethod: None=0, DayaLoan=1, DirectPurchase=2, Manual=3

  Defaults to ROLLBACK. Uncomment COMMIT after verifying PRINT output.
  Run 10-Diagnose_Manualy_Transaction_Map.sql first.
*/

SET NOCOUNT ON;
SET XACT_ABORT ON;

BEGIN TRAN;

DECLARE @Now DATETIME2 = SYSUTCDATETIME();

DECLARE @BasePackageId BIGINT;
DECLARE @BasePackagePrice BIGINT;

SELECT TOP (1)
    @BasePackageId = Id,
    @BasePackagePrice = Price
FROM CMS.Packages
WHERE IsDeleted = 0 AND IsBasePackage = 1
ORDER BY Id;

IF @BasePackageId IS NULL
    THROW 50001, 'Base package not found.', 1;

------------------------------------------------------------
-- Scope: users linked to manualy transactions
-- (duplicate WH→Tx links exist from migration; rank by mobile match + charge amount + date)
------------------------------------------------------------
DECLARE @ManualyUsers TABLE (
    UserId BIGINT NOT NULL PRIMARY KEY,
    ManualyTxId BIGINT NULL,
    LinkSource NVARCHAR(50) NULL
);

SELECT t.Id AS TxId, t.RefId, t.Amount, t.PaymentDate, t.CreatedBy, t.LastModifiedBy
INTO #ManualyTx
FROM CMS.Transactions t
WHERE t.IsDeleted = 0 AND t.RefId LIKE N'manualy%';

SELECT
    mt.TxId,
    w.UserId,
    h.Id AS WhId,
    h.ChangeValue,
    CASE
        WHEN NULLIF(LTRIM(RTRIM(mt.CreatedBy)), N'') LIKE N'09%'
             AND u.Mobile = NULLIF(LTRIM(RTRIM(mt.CreatedBy)), N'') THEN 1
        WHEN NULLIF(LTRIM(RTRIM(mt.LastModifiedBy)), N'') LIKE N'09%'
             AND u.Mobile = NULLIF(LTRIM(RTRIM(mt.LastModifiedBy)), N'') THEN 1
        ELSE 0
    END AS MobileMatch,
    CASE WHEN h.ChangeValue >= mt.Amount THEN 1 ELSE 0 END AS FullCharge,
    ABS(DATEDIFF(SECOND, h.Created, mt.PaymentDate)) AS TimeDeltaSec
INTO #WhLinks
FROM #ManualyTx mt
INNER JOIN CMS.UserWalletHistories h ON h.RefrenceId = mt.TxId AND h.IsDeleted = 0
INNER JOIN CMS.UserWallets w ON w.Id = h.WalletId AND w.IsDeleted = 0
INNER JOIN CMS.Users u ON u.Id = w.UserId AND u.IsDeleted = 0;

SELECT UserId, TxId, WhId, MobileMatch, FullCharge,
       ROW_NUMBER() OVER (
           PARTITION BY TxId
           ORDER BY MobileMatch DESC, FullCharge DESC, TimeDeltaSec ASC, WhId ASC
       ) AS rn
INTO #BestWhPerTx
FROM #WhLinks;

INSERT INTO @ManualyUsers (UserId, ManualyTxId, LinkSource)
SELECT b.UserId, b.TxId, N'WH_REF_BEST'
FROM #BestWhPerTx b
WHERE b.rn = 1
  AND (b.MobileMatch = 1 OR b.FullCharge = 1);

INSERT INTO @ManualyUsers (UserId, ManualyTxId, LinkSource)
SELECT DISTINCT w.UserId, t.Id, N'WH_CREATEDBY_HINT'
FROM CMS.UserWalletHistories h
INNER JOIN CMS.UserWallets w ON w.Id = h.WalletId AND w.IsDeleted = 0
INNER JOIN CMS.Transactions t ON t.Id = TRY_CAST(h.CreatedBy AS BIGINT)
    AND t.IsDeleted = 0 AND t.RefId LIKE N'manualy%'
INNER JOIN CMS.Users u ON u.Id = w.UserId AND u.IsDeleted = 0
WHERE h.IsDeleted = 0
  AND (h.RefrenceId IS NULL OR h.RefrenceId = 0)
  AND TRY_CAST(h.CreatedBy AS BIGINT) > 0
  AND (
        NULLIF(LTRIM(RTRIM(t.CreatedBy)), N'') NOT LIKE N'09%'
     OR u.Mobile IN (
            NULLIF(LTRIM(RTRIM(t.CreatedBy)), N''),
            NULLIF(LTRIM(RTRIM(t.LastModifiedBy)), N'')
        )
  )
  AND NOT EXISTS (SELECT 1 FROM @ManualyUsers m WHERE m.UserId = w.UserId);

INSERT INTO @ManualyUsers (UserId, ManualyTxId, LinkSource)
SELECT DISTINCT u.Id, t.Id, N'TX_MOBILE'
FROM CMS.Transactions t
INNER JOIN CMS.Users u ON u.IsDeleted = 0
    AND u.Mobile IN (
        NULLIF(LTRIM(RTRIM(t.CreatedBy)), N''),
        NULLIF(LTRIM(RTRIM(t.LastModifiedBy)), N'')
    )
WHERE t.IsDeleted = 0 AND t.RefId LIKE N'manualy%'
  AND NOT EXISTS (SELECT 1 FROM @ManualyUsers m WHERE m.UserId = u.Id);

-- Txs without mobile on row: keep best full-charge WH only (early batch 23-31)
INSERT INTO @ManualyUsers (UserId, ManualyTxId, LinkSource)
SELECT b.UserId, b.TxId, N'WH_REF_NO_MOBILE'
FROM #BestWhPerTx b
INNER JOIN #ManualyTx mt ON mt.TxId = b.TxId
WHERE b.rn = 1
  AND b.FullCharge = 1
  AND (NULLIF(LTRIM(RTRIM(mt.CreatedBy)), N'') IS NULL OR NULLIF(LTRIM(RTRIM(mt.CreatedBy)), N'') NOT LIKE N'09%')
  AND (NULLIF(LTRIM(RTRIM(mt.LastModifiedBy)), N'') IS NULL OR NULLIF(LTRIM(RTRIM(mt.LastModifiedBy)), N'') NOT LIKE N'09%')
  AND NOT EXISTS (SELECT 1 FROM @ManualyUsers m WHERE m.UserId = b.UserId);

DROP TABLE #BestWhPerTx;
DROP TABLE #WhLinks;
DROP TABLE #ManualyTx;

DECLARE @ScopeCount INT = (SELECT COUNT(*) FROM @ManualyUsers);
PRINT CONCAT('manualy scope users: ', @ScopeCount);
PRINT CONCAT('BasePackageId=', @BasePackageId, ' Price=', @BasePackagePrice);

SELECT mu.UserId, u.Mobile, u.FirstName, u.LastName,
       u.PackagePurchaseMethod, mu.ManualyTxId, mu.LinkSource
FROM @ManualyUsers mu
INNER JOIN CMS.Users u ON u.Id = mu.UserId AND u.IsDeleted = 0
ORDER BY mu.UserId;

------------------------------------------------------------
-- Preview
------------------------------------------------------------
SELECT 'Users with manualy Tx resolved' AS CheckName, COUNT(*) AS Cnt
FROM @ManualyUsers WHERE ManualyTxId IS NOT NULL
UNION ALL
SELECT 'Users in scope without resolved Tx', COUNT(*)
FROM @ManualyUsers WHERE ManualyTxId IS NULL
UNION ALL
SELECT 'Broken WH rows fixable via CreatedBy hint', COUNT(*)
FROM CMS.UserWalletHistories h
INNER JOIN CMS.UserWallets w ON w.Id = h.WalletId AND w.IsDeleted = 0
INNER JOIN @ManualyUsers mu ON mu.UserId = w.UserId
INNER JOIN CMS.Transactions t ON t.Id = TRY_CAST(h.CreatedBy AS BIGINT)
    AND t.IsDeleted = 0 AND t.RefId LIKE N'manualy%'
WHERE h.IsDeleted = 0
  AND (h.RefrenceId IS NULL OR h.RefrenceId = 0)
  AND TRY_CAST(h.CreatedBy AS BIGINT) > 0
UNION ALL
SELECT 'Missing UPP in scope', COUNT(*)
FROM @ManualyUsers mu
WHERE NOT EXISTS (
    SELECT 1 FROM CMS.UserPackagePurchases upp
    WHERE upp.UserId = mu.UserId AND upp.IsDeleted = 0
);

------------------------------------------------------------
-- 1) Fix broken WH.RefrenceId (CreatedBy hint → existing manualy Tx)
------------------------------------------------------------
UPDATE h
SET
    h.RefrenceId = t.Id,
    h.LastModified = @Now
FROM CMS.UserWalletHistories h
INNER JOIN CMS.UserWallets w ON w.Id = h.WalletId AND w.IsDeleted = 0
INNER JOIN @ManualyUsers mu ON mu.UserId = w.UserId
INNER JOIN CMS.Transactions t ON t.Id = TRY_CAST(h.CreatedBy AS BIGINT)
    AND t.IsDeleted = 0
    AND t.RefId LIKE N'manualy%'
    AND t.PaymentStatus = 0
WHERE h.IsDeleted = 0
  AND (h.RefrenceId IS NULL OR h.RefrenceId = 0)
  AND TRY_CAST(h.CreatedBy AS BIGINT) > 0;

PRINT CONCAT('WalletHistory RefrenceId fixed: ', @@ROWCOUNT);

------------------------------------------------------------
-- 2) Users — DayaLoan → Manual
------------------------------------------------------------
UPDATE u
SET
    u.PackagePurchaseMethod = 3,
    u.HasReceivedDayaCredit = 0,
    u.DayaCreditReceivedAt = NULL,
    u.LastModified = @Now
FROM CMS.Users u
INNER JOIN @ManualyUsers mu ON mu.UserId = u.Id
WHERE u.IsDeleted = 0
  AND (
        u.PackagePurchaseMethod = 1
     OR u.HasReceivedDayaCredit = 1
     OR u.DayaCreditReceivedAt IS NOT NULL
  );

PRINT CONCAT('Users updated: ', @@ROWCOUNT);

------------------------------------------------------------
-- 3) ClubMemberships
------------------------------------------------------------
UPDATE m
SET m.PurchaseMethod = 3, m.LastModified = @Now
FROM CMS.ClubMemberships m
INNER JOIN @ManualyUsers mu ON mu.UserId = m.UserId
WHERE m.IsDeleted = 0 AND m.PurchaseMethod IN (0, 1);

PRINT CONCAT('ClubMemberships updated: ', @@ROWCOUNT);

------------------------------------------------------------
-- 4) ClubMembershipCycles
------------------------------------------------------------
UPDATE c
SET c.PurchaseMethod = 3, c.LastModified = @Now
FROM CMS.ClubMembershipCycles c
INNER JOIN @ManualyUsers mu ON mu.UserId = c.UserId
WHERE c.IsDeleted = 0 AND c.PurchaseMethod IN (0, 1);

PRINT CONCAT('ClubMembershipCycles updated: ', @@ROWCOUNT);

------------------------------------------------------------
-- 5) UserPackagePurchases (existing rows Daya → Manual)
------------------------------------------------------------
UPDATE upp
SET upp.PurchaseMethod = 3, upp.LastModified = @Now
FROM CMS.UserPackagePurchases upp
INNER JOIN @ManualyUsers mu ON mu.UserId = upp.UserId
WHERE upp.IsDeleted = 0 AND upp.PurchaseMethod = 1;

PRINT CONCAT('UserPackagePurchases updated: ', @@ROWCOUNT);

------------------------------------------------------------
-- 6) Soft-delete stub DayaLoanContracts
------------------------------------------------------------
UPDATE d
SET d.IsDeleted = 1, d.LastModified = @Now
FROM CMS.DayaLoanContracts d
INNER JOIN @ManualyUsers mu ON mu.UserId = d.UserId
WHERE d.IsDeleted = 0
  AND d.IsProcessed = 0
  AND d.TransactionId IS NULL
  AND d.ProcessedDate IS NULL;

PRINT CONCAT('DayaLoanContracts soft-deleted (stubs): ', @@ROWCOUNT);

------------------------------------------------------------
-- 7) Resolve best manualy Tx per user (post WH fix)
------------------------------------------------------------
;WITH TxCandidates AS (
    SELECT mu.UserId, t.Id AS TxId, N'WH_REF' AS Src, 1 AS Pri
    FROM @ManualyUsers mu
    INNER JOIN CMS.UserWallets w ON w.UserId = mu.UserId AND w.IsDeleted = 0
    INNER JOIN CMS.UserWalletHistories h ON h.WalletId = w.Id AND h.IsDeleted = 0
    INNER JOIN CMS.Transactions t ON t.Id = h.RefrenceId
        AND t.IsDeleted = 0 AND t.RefId LIKE N'manualy%' AND t.PaymentStatus = 0

    UNION ALL

    SELECT mu.UserId, t.Id, N'WH_HINT', 2
    FROM @ManualyUsers mu
    INNER JOIN CMS.UserWallets w ON w.UserId = mu.UserId AND w.IsDeleted = 0
    INNER JOIN CMS.UserWalletHistories h ON h.WalletId = w.Id AND h.IsDeleted = 0
    INNER JOIN CMS.Transactions t ON t.Id = TRY_CAST(h.CreatedBy AS BIGINT)
        AND t.IsDeleted = 0 AND t.RefId LIKE N'manualy%' AND t.PaymentStatus = 0
    WHERE (h.RefrenceId IS NULL OR h.RefrenceId = 0)
      AND TRY_CAST(h.CreatedBy AS BIGINT) > 0

    UNION ALL

    SELECT mu.UserId, t.Id, N'TX_MOBILE', 3
    FROM @ManualyUsers mu
    INNER JOIN CMS.Users u ON u.Id = mu.UserId AND u.IsDeleted = 0
    INNER JOIN CMS.Transactions t ON t.IsDeleted = 0
        AND t.RefId LIKE N'manualy%' AND t.PaymentStatus = 0
        AND u.Mobile IN (
            NULLIF(LTRIM(RTRIM(t.CreatedBy)), N''),
            NULLIF(LTRIM(RTRIM(t.LastModifiedBy)), N'')
        )

    UNION ALL

    SELECT mu.UserId, mu.ManualyTxId, mu.LinkSource, 4
    FROM @ManualyUsers mu
    WHERE mu.ManualyTxId IS NOT NULL
),
BestTx AS (
    SELECT UserId, TxId, Src,
           ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY Pri, TxId DESC) AS rn
    FROM TxCandidates
    WHERE TxId IS NOT NULL
)
SELECT
    mu.UserId,
    bt.TxId,
    bt.Src AS TxSource,
    COALESCE(NULLIF(cm.LastPackageId, 0), NULLIF(cm.FirstPackageId, 0), @BasePackageId) AS PackageId,
    COALESCE(t.Amount, @BasePackagePrice) AS Amount,
    COALESCE(t.PaymentDate, cm.ActivatedAt, @Now) AS PurchasedAt
INTO #ManualyUppPlan
FROM @ManualyUsers mu
LEFT JOIN BestTx bt ON bt.UserId = mu.UserId AND bt.rn = 1
LEFT JOIN CMS.Transactions t ON t.Id = bt.TxId AND t.IsDeleted = 0
LEFT JOIN CMS.ClubMemberships cm ON cm.UserId = mu.UserId AND cm.IsDeleted = 0
WHERE NOT EXISTS (
    SELECT 1 FROM CMS.UserPackagePurchases upp
    WHERE upp.UserId = mu.UserId AND upp.IsDeleted = 0
);

DECLARE @UppPlanCount INT = (SELECT COUNT(*) FROM #ManualyUppPlan);
PRINT CONCAT('UPP to create: ', @UppPlanCount);

SELECT UserId, TxId, TxSource, PackageId, Amount, PurchasedAt,
       CASE WHEN TxId IS NULL THEN N'SKIP_NO_MANUALY_TX' ELSE N'CREATE_UPP' END AS PlanAction
FROM #ManualyUppPlan
ORDER BY UserId;

DECLARE @UserId BIGINT;
DECLARE @TxId BIGINT;
DECLARE @PackageId BIGINT;
DECLARE @Amount BIGINT;
DECLARE @PurchasedAt DATETIME2;
DECLARE @CreatedUpp INT = 0;
DECLARE @SkippedNoTx INT = 0;

DECLARE curUpp CURSOR LOCAL FAST_FORWARD FOR
    SELECT UserId, TxId, PackageId, Amount, PurchasedAt
    FROM #ManualyUppPlan;

OPEN curUpp;
FETCH NEXT FROM curUpp INTO @UserId, @TxId, @PackageId, @Amount, @PurchasedAt;

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @TxId IS NULL OR @PackageId IS NULL OR @Amount IS NULL OR @Amount <= 0
    BEGIN
        SET @SkippedNoTx = @SkippedNoTx + 1;
    END
    ELSE
    BEGIN
        INSERT INTO CMS.UserPackagePurchases
        (
            UserId, PackageId, PurchaseMethod, PurchasedAt, Amount,
            OrderId, TransactionId, Created, CreatedBy, LastModified, LastModifiedBy, IsDeleted
        )
        VALUES
        (
            @UserId, @PackageId, 3,
            @PurchasedAt, @Amount,
            NULL, @TxId, @PurchasedAt, NULL, @PurchasedAt, NULL, 0
        );
        SET @CreatedUpp = @CreatedUpp + 1;
    END

    FETCH NEXT FROM curUpp INTO @UserId, @TxId, @PackageId, @Amount, @PurchasedAt;
END

CLOSE curUpp;
DEALLOCATE curUpp;
DROP TABLE #ManualyUppPlan;

PRINT CONCAT('UPP created: ', @CreatedUpp, ' | Skipped (no manualy Tx): ', @SkippedNoTx);

------------------------------------------------------------
-- 8) Missing WH for resolved manualy Tx (history-only, no wallet charge)
------------------------------------------------------------
;WITH TxCandidates AS (
    SELECT mu.UserId, t.Id AS TxId, 1 AS Pri
    FROM @ManualyUsers mu
    INNER JOIN CMS.UserWallets w ON w.UserId = mu.UserId AND w.IsDeleted = 0
    INNER JOIN CMS.UserWalletHistories h ON h.WalletId = w.Id AND h.IsDeleted = 0
    INNER JOIN CMS.Transactions t ON t.Id = h.RefrenceId
        AND t.IsDeleted = 0 AND t.RefId LIKE N'manualy%'

    UNION ALL

    SELECT mu.UserId, t.Id, 2
    FROM @ManualyUsers mu
    INNER JOIN CMS.Users u ON u.Id = mu.UserId AND u.IsDeleted = 0
    INNER JOIN CMS.Transactions t ON t.IsDeleted = 0 AND t.RefId LIKE N'manualy%'
        AND u.Mobile IN (
            NULLIF(LTRIM(RTRIM(t.CreatedBy)), N''),
            NULLIF(LTRIM(RTRIM(t.LastModifiedBy)), N'')
        )
),
BestTx AS (
    SELECT UserId, TxId,
           ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY Pri, TxId DESC) AS rn
    FROM TxCandidates
)
SELECT
    bt.UserId,
    bt.TxId,
    w.Id AS WalletId,
    COALESCE(t.Amount, @BasePackagePrice) AS Amount,
    COALESCE(t.PaymentDate, @Now) AS HistoryAt,
    COALESCE(
        NULLIF(cm.LastPackageId, 0),
        NULLIF(cm.FirstPackageId, 0),
        @BasePackageId
    ) AS PackageId,
    CAST(ROUND(COALESCE(t.Amount, @BasePackagePrice) * COALESCE(p.DiscountMultiplier, 2.0), 0) AS BIGINT) AS DiscountAmount,
    COALESCE(w.NetworkBalance, 0) AS NetworkBalance
INTO #WhToCreate
FROM BestTx bt
INNER JOIN CMS.Transactions t ON t.Id = bt.TxId AND t.IsDeleted = 0
LEFT JOIN CMS.UserWallets w ON w.UserId = bt.UserId AND w.IsDeleted = 0
LEFT JOIN CMS.ClubMemberships cm ON cm.UserId = bt.UserId AND cm.IsDeleted = 0
LEFT JOIN CMS.Packages p ON p.Id = COALESCE(
    NULLIF(cm.LastPackageId, 0),
    NULLIF(cm.FirstPackageId, 0),
    @BasePackageId
) AND p.IsDeleted = 0
WHERE bt.rn = 1
  AND NOT EXISTS (
      SELECT 1
      FROM CMS.UserWalletHistories h
      INNER JOIN CMS.UserWallets wh ON wh.Id = h.WalletId AND wh.IsDeleted = 0
      WHERE wh.UserId = bt.UserId
        AND h.IsDeleted = 0
        AND h.RefrenceId = bt.TxId
  );

DECLARE @WhPlanCount INT = (SELECT COUNT(*) FROM #WhToCreate);
PRINT CONCAT('WalletHistory to create (no charge): ', @WhPlanCount);

SELECT UserId, TxId, WalletId, Amount, HistoryAt, N'CREATE_HISTORY_ONLY' AS PlanAction
FROM #WhToCreate
ORDER BY UserId;

DECLARE @WalletId BIGINT;
DECLARE @DiscountAmount BIGINT;
DECLARE @HistoryAt DATETIME2;
DECLARE @NetworkBalance BIGINT;
DECLARE @CreatedWh INT = 0;

DECLARE curWh CURSOR LOCAL FAST_FORWARD FOR
    SELECT UserId, TxId, WalletId, Amount, PackageId, DiscountAmount, HistoryAt, NetworkBalance
    FROM #WhToCreate;

OPEN curWh;
FETCH NEXT FROM curWh INTO
    @UserId, @TxId, @WalletId, @Amount, @PackageId, @DiscountAmount, @HistoryAt, @NetworkBalance;

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @WalletId IS NULL
    BEGIN
        INSERT INTO CMS.UserWallets
            (UserId, Balance, NetworkBalance, DiscountBalance, WalletMode, Created, LastModified, IsDeleted)
        VALUES (@UserId, 0, 0, 0, 0, @HistoryAt, @HistoryAt, 0);
        SET @WalletId = SCOPE_IDENTITY();
        SET @NetworkBalance = 0;
    END

    INSERT INTO CMS.UserWalletHistories
    (
        WalletId, CurrentBalance, ChangeValue, CurrentNetworkBalance, ChangeNerworkValue,
        CurrentDiscountBalance, ChangeDiscountValue, IsIncrease, RefrenceId, PackageId,
        Created, CreatedBy, LastModified, LastModifiedBy, IsDeleted
    )
    VALUES
    (
        @WalletId, 0, @Amount, @NetworkBalance, 0,
        0, @DiscountAmount, 1, @TxId, @PackageId,
        @HistoryAt, NULL, @HistoryAt, NULL, 0
    );

    SET @CreatedWh = @CreatedWh + 1;

    FETCH NEXT FROM curWh INTO
        @UserId, @TxId, @WalletId, @Amount, @PackageId, @DiscountAmount, @HistoryAt, @NetworkBalance;
END

CLOSE curWh;
DEALLOCATE curWh;
DROP TABLE #WhToCreate;

PRINT CONCAT('WalletHistory created (no charge): ', @CreatedWh);

------------------------------------------------------------
-- Verify
------------------------------------------------------------
SELECT 'Users still Daya in scope' AS CheckName, COUNT(*) AS Cnt
FROM CMS.Users u
INNER JOIN @ManualyUsers mu ON mu.UserId = u.Id
WHERE u.IsDeleted = 0 AND u.PackagePurchaseMethod = 1
UNION ALL
SELECT 'Still missing UPP in scope', COUNT(*)
FROM @ManualyUsers mu
WHERE NOT EXISTS (
    SELECT 1 FROM CMS.UserPackagePurchases upp
    WHERE upp.UserId = mu.UserId AND upp.IsDeleted = 0
)
UNION ALL
SELECT 'Broken WH Ref=0 with valid hint remaining', COUNT(*)
FROM CMS.UserWalletHistories h
INNER JOIN CMS.UserWallets w ON w.Id = h.WalletId AND w.IsDeleted = 0
INNER JOIN @ManualyUsers mu ON mu.UserId = w.UserId
WHERE h.IsDeleted = 0
  AND (h.RefrenceId IS NULL OR h.RefrenceId = 0)
  AND TRY_CAST(h.CreatedBy AS BIGINT) > 0
  AND EXISTS (
      SELECT 1 FROM CMS.Transactions t
      WHERE t.Id = TRY_CAST(h.CreatedBy AS BIGINT)
        AND t.IsDeleted = 0 AND t.RefId LIKE N'manualy%'
  )
UNION ALL
SELECT 'Active stub Daya contracts in scope', COUNT(*)
FROM CMS.DayaLoanContracts d
INNER JOIN @ManualyUsers mu ON mu.UserId = d.UserId
WHERE d.IsDeleted = 0
  AND d.IsProcessed = 0
  AND d.TransactionId IS NULL
  AND d.ProcessedDate IS NULL;

SELECT u.Id AS UserId, u.Mobile, u.FirstName, u.LastName,
       u.PackagePurchaseMethod,
       (SELECT COUNT(*) FROM CMS.UserPackagePurchases upp
        WHERE upp.UserId = u.Id AND upp.IsDeleted = 0) AS UppCnt,
       (SELECT COUNT(*) FROM CMS.UserWalletHistories h
        INNER JOIN CMS.UserWallets w ON w.Id = h.WalletId
        WHERE w.UserId = u.Id AND h.IsDeleted = 0) AS WhCnt
FROM CMS.Users u
INNER JOIN @ManualyUsers mu ON mu.UserId = u.Id
WHERE u.IsDeleted = 0
ORDER BY u.Id;

ROLLBACK;
-- COMMIT;

PRINT 'Done (rolled back by default).';
