WITH terminal_orders AS (
    SELECT id,
           tenant_id,
           user_id,
           wallet_debit_cents,
           title,
           error_message
    FROM media_supply_orders
    WHERE supplier = 'meijiequan'
      AND status IN ('queued', 'submitting')
      AND wallet_debited_at IS NOT NULL
      AND wallet_refunded_at IS NULL
      AND wallet_debit_cents > 0
      AND deleted_at IS NULL
      AND (
          error_message ILIKE 'failed to refresh supplier price%'
          OR error_message ILIKE 'meijiequan create order failed:%'
          OR error_message ILIKE 'supplier cost increased above locked sell price%'
      )
),
wallet_snapshot AS (
    SELECT o.*,
           w.balance_cents AS balance_before,
           SUM(o.wallet_debit_cents) OVER (
               PARTITION BY o.tenant_id, o.user_id
               ORDER BY o.id
               ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
           ) AS running_refund
    FROM terminal_orders o
    JOIN media_supply_user_wallets w
      ON w.tenant_id = o.tenant_id
     AND w.user_id = o.user_id
),
refund_totals AS (
    SELECT tenant_id,
           user_id,
           SUM(wallet_debit_cents) AS total_refund
    FROM terminal_orders
    GROUP BY tenant_id, user_id
),
updated_wallets AS (
    UPDATE media_supply_user_wallets w
    SET balance_cents = w.balance_cents + rt.total_refund,
        updated_at = NOW()
    FROM refund_totals rt
    WHERE w.tenant_id = rt.tenant_id
      AND w.user_id = rt.user_id
    RETURNING w.tenant_id, w.user_id
),
updated_orders AS (
    UPDATE media_supply_orders o
    SET status = 'failed',
        wallet_refunded_at = NOW(),
        next_attempt_at = NOW(),
        updated_at = NOW()
    FROM terminal_orders t
    WHERE o.id = t.id
    RETURNING o.id
),
updated_items AS (
    UPDATE media_supply_order_items i
    SET status = 'failed',
        updated_at = NOW()
    FROM terminal_orders t
    WHERE i.order_id = t.id
      AND i.status IN ('queued', 'submitting')
    RETURNING i.id
)
INSERT INTO media_supply_wallet_ledgers (
    tenant_id,
    user_id,
    order_id,
    delta_cents,
    balance_after_cents,
    reason,
    note,
    created_by
)
SELECT ws.tenant_id,
       ws.user_id,
       ws.id,
       ws.wallet_debit_cents,
       ws.balance_before + ws.running_refund,
       'order_refund',
       COALESCE(NULLIF(ws.error_message, ''), ws.title),
       ws.user_id
FROM wallet_snapshot ws
JOIN updated_orders uo ON uo.id = ws.id;
