-- Reclassify unsettled withdrawals without changing their original journal entries.
START TRANSACTION;

UPDATE WalletBalance b
JOIN (
 SELECT walletId, asset, SUM(amount) AS amount
 FROM Withdrawal WHERE status IN ('pending_review', 'approved')
 GROUP BY walletId, asset
) pending ON CAST(b.walletId AS BINARY) = CAST(pending.walletId AS BINARY)
 AND CAST(b.asset AS BINARY) = CAST(pending.asset AS BINARY)
SET b.locked = b.locked - pending.amount;

INSERT INTO LedgerOperation (id, userId, requestKey, fingerprint, kind, asset, amount)
SELECT UUID(), userId, CONCAT('wd:', id, ':reclass'), fingerprint, 'withdrawal_reclass', asset, amount
FROM Withdrawal WHERE status IN ('pending_review', 'approved');

INSERT INTO LedgerEntry (id, operationId, account, delta)
SELECT UUID(), o.id, CONCAT(w.mode, ':', w.id, ':locked'), -r.amount
FROM Withdrawal r JOIN Wallet w ON CAST(w.id AS BINARY) = CAST(r.walletId AS BINARY)
JOIN LedgerOperation o ON CAST(o.userId AS BINARY) = CAST(r.userId AS BINARY)
 AND CAST(o.requestKey AS BINARY) = CAST(CONCAT('wd:', r.id, ':reclass') AS BINARY)
UNION ALL
SELECT UUID(), o.id, CONCAT(w.mode, ':', w.id, ':withdrawal'), r.amount
FROM Withdrawal r JOIN Wallet w ON CAST(w.id AS BINARY) = CAST(r.walletId AS BINARY)
JOIN LedgerOperation o ON CAST(o.userId AS BINARY) = CAST(r.userId AS BINARY)
 AND CAST(o.requestKey AS BINARY) = CAST(CONCAT('wd:', r.id, ':reclass') AS BINARY);

COMMIT;

