-- 修复代理主钱包扣款流水余额快照
-- 历史扣款流水曾在扣款后重新读取钱包，导致 balance_before/balance_after 多扣一次。
-- 以成功流水的 amount 顺序累计值为准，重算主钱包流水快照，并同步主钱包剩余余额。

WITH ordered_transactions AS (
    SELECT
        t.id,
        SUM(t.amount) OVER (
            PARTITION BY t.agent_wallet_id
            ORDER BY t.created_at, t.id
            ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
        ) AS repaired_balance_after,
        SUM(t.amount) OVER (
            PARTITION BY t.agent_wallet_id
            ORDER BY t.created_at, t.id
            ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
        ) - t.amount AS repaired_balance_before
    FROM tb_agent_wallet_transaction t
    INNER JOIN tb_agent_wallet w ON w.id = t.agent_wallet_id
    WHERE w.wallet_type = 'main'
      AND w.deleted_at IS NULL
      AND t.deleted_at IS NULL
      AND t.status = 1
),
updated_transactions AS (
    UPDATE tb_agent_wallet_transaction t
    SET
        balance_before = ordered_transactions.repaired_balance_before,
        balance_after = ordered_transactions.repaired_balance_after,
        updated_at = NOW()
    FROM ordered_transactions
    WHERE t.id = ordered_transactions.id
      AND (
          t.balance_before <> ordered_transactions.repaired_balance_before
          OR t.balance_after <> ordered_transactions.repaired_balance_after
      )
    RETURNING t.agent_wallet_id
),
wallet_balances AS (
    SELECT
        t.agent_wallet_id,
        SUM(t.amount) AS repaired_balance
    FROM tb_agent_wallet_transaction t
    INNER JOIN tb_agent_wallet w ON w.id = t.agent_wallet_id
    WHERE w.wallet_type = 'main'
      AND w.deleted_at IS NULL
      AND t.deleted_at IS NULL
      AND t.status = 1
    GROUP BY t.agent_wallet_id
)
UPDATE tb_agent_wallet w
SET
    balance = wallet_balances.repaired_balance,
    updated_at = NOW()
FROM wallet_balances
WHERE w.id = wallet_balances.agent_wallet_id
  AND w.wallet_type = 'main'
  AND w.deleted_at IS NULL
  AND w.balance <> wallet_balances.repaired_balance;
