-- +goose Up

-- 押金暂扣：客服可对进行中订单的押金退款进行暂扣，订单照常结算/关闭/仲裁，
-- 但本应原路退给租客的押金部分不自动退，挂起为“已暂扣”，后续由客服手动归还。
ALTER TABLE rental_orders
  ADD COLUMN deposit_hold_status VARCHAR(16) NOT NULL DEFAULT 'none' COMMENT '押金暂扣状态: none无/held已暂扣/released已归还' AFTER refunded_at,
  ADD COLUMN deposit_hold_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '实际暂扣的押金金额(分)，结算时确定' AFTER deposit_hold_status,
  ADD COLUMN deposit_hold_reason VARCHAR(255) NOT NULL DEFAULT '' COMMENT '暂扣原因' AFTER deposit_hold_amount_cent,
  ADD COLUMN deposit_held_by BIGINT UNSIGNED NULL COMMENT '暂扣操作管理员' AFTER deposit_hold_reason,
  ADD COLUMN deposit_held_at DATETIME NULL COMMENT '暂扣时间' AFTER deposit_held_by,
  ADD COLUMN deposit_hold_released_at DATETIME NULL COMMENT '押金归还时间' AFTER deposit_held_at;

CREATE INDEX idx_deposit_hold_status ON rental_orders (deposit_hold_status);

INSERT INTO permissions (code, name, resource, action)
VALUES ('order:deposit_hold', '押金暂扣与归还', 'order', 'deposit_hold');

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r, permissions p
WHERE r.code IN ('cs', 'ops') AND p.code = 'order:deposit_hold';

-- +goose Down

DROP INDEX idx_deposit_hold_status ON rental_orders;

ALTER TABLE rental_orders
  DROP COLUMN deposit_hold_status,
  DROP COLUMN deposit_hold_amount_cent,
  DROP COLUMN deposit_hold_reason,
  DROP COLUMN deposit_held_by,
  DROP COLUMN deposit_held_at,
  DROP COLUMN deposit_hold_released_at;

DELETE rp FROM role_permissions rp
JOIN permissions p ON p.id = rp.permission_id
WHERE p.code = 'order:deposit_hold';

DELETE FROM permissions WHERE code = 'order:deposit_hold';
