-- AlterTable
ALTER TABLE "wallet_transactions" ADD COLUMN IF NOT EXISTS "business_key" VARCHAR(128);

-- CreateIndex
CREATE UNIQUE INDEX IF NOT EXISTS "wallet_transactions_business_key_key" ON "wallet_transactions"("business_key");

-- Deduplicate legacy settlement preview items before enforcing idempotency.
WITH ranked_settlement_items AS (
  SELECT
    "id",
    ROW_NUMBER() OVER (
      PARTITION BY "batch_id", "bet_id"
      ORDER BY "id"
    ) AS row_num
  FROM "settlement_items"
)
DELETE FROM "settlement_items" si
USING ranked_settlement_items r
WHERE si."id" = r."id"
  AND r.row_num > 1;

-- CreateIndex
CREATE UNIQUE INDEX IF NOT EXISTS "settlement_items_batch_id_bet_id_key" ON "settlement_items"("batch_id", "bet_id");
