DO $$
BEGIN
    IF EXISTS (
        SELECT 1
          FROM tb_agent_wallet_transaction
         WHERE reference_type = 'refund'
           AND transaction_type = 'refund'
           AND status = 1
           AND reference_id IS NOT NULL
         GROUP BY reference_type, reference_id, transaction_type
        HAVING COUNT(*) > 1
    ) THEN
        RAISE EXCEPTION '存在重复的代理主钱包成功退款流水，禁止创建唯一索引';
    END IF;
END
$$;

COMMENT ON COLUMN tb_agent_wallet_transaction.transaction_type IS '交易类型：recharge-充值 adjustment-人工调整 deduct-扣款 refund-退款 commission-分佣 withdrawal-提现';
COMMENT ON COLUMN tb_agent_wallet_transaction.reference_type IS '关联业务类型：order commission withdrawal topup refund exchange manual_adjustment';

CREATE UNIQUE INDEX uq_agent_wallet_refund_reference
    ON tb_agent_wallet_transaction (reference_type, reference_id, transaction_type)
    WHERE reference_type = 'refund'
      AND transaction_type = 'refund'
      AND status = 1;

COMMENT ON INDEX uq_agent_wallet_refund_reference IS '保证每张退款单最多存在一条代理主钱包成功退款流水，软删除不能绕过资金幂等';
