DELETE FROM qipai_schema_migrations WHERE version = '2026081006';

ALTER TABLE qipai_cleaning_settlement_items
  DROP FOREIGN KEY fk_qipai_cleaning_settlement_items_reversal;

DELETE reversed
FROM qipai_cleaning_settlement_items reversed
INNER JOIN qipai_cleaning_settlement_items active
  ON active.tenant_id = reversed.tenant_id
  AND active.task_id = reversed.task_id
  AND active.cleaner_user_id = reversed.cleaner_user_id
  AND active.reversed_at IS NULL
WHERE reversed.reversed_at IS NOT NULL;

DELETE older
FROM qipai_cleaning_settlement_items older
INNER JOIN qipai_cleaning_settlement_items newer
  ON newer.tenant_id = older.tenant_id
  AND newer.task_id = older.task_id
  AND newer.cleaner_user_id = older.cleaner_user_id
  AND newer.id > older.id
WHERE older.reversed_at IS NOT NULL AND newer.reversed_at IS NOT NULL;

ALTER TABLE qipai_cleaning_settlement_items
  DROP INDEX uq_qipai_cleaning_settlement_active_share,
  DROP INDEX idx_qipai_cleaning_settlement_item_reversal,
  DROP COLUMN active_share_key,
  DROP COLUMN reversed_at,
  DROP COLUMN reversal_id,
  ADD UNIQUE KEY uq_qipai_cleaning_settlement_item_task_user
    (tenant_id, task_id, cleaner_user_id);

ALTER TABLE qipai_cleaning_settlements
  DROP FOREIGN KEY fk_qipai_cleaning_settlements_cancelled_by,
  DROP INDEX idx_qipai_cleaning_settlement_cancelled,
  DROP INDEX uq_qipai_cleaning_settlement_payout_request,
  DROP COLUMN payout_request_key,
  DROP COLUMN payout_request_no,
  DROP COLUMN cancelled_at,
  DROP COLUMN cancelled_by;

DROP TABLE IF EXISTS qipai_cleaning_settlement_events;
DROP TABLE IF EXISTS qipai_cleaning_settlement_reversals;
