ALTER TABLE tb_order
    ADD COLUMN idempotency_key VARCHAR(64) NOT NULL DEFAULT '';

COMMENT ON COLUMN tb_order.idempotency_key IS '订单创建幂等指纹(SHA-256)，用于钱包订单事务级防重';

CREATE INDEX idx_order_idempotency_key
    ON tb_order (idempotency_key, created_at DESC)
    WHERE idempotency_key <> '';

COMMENT ON INDEX idx_order_idempotency_key IS '支持在幂等窗口内定位已提交的钱包订单';

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
          FROM tb_agent_wallet_transaction
         WHERE reference_type = 'order'
           AND transaction_type = 'deduct'
           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
$$;

CREATE UNIQUE INDEX uq_agent_wallet_order_debit
    ON tb_agent_wallet_transaction (reference_type, reference_id, transaction_type)
    WHERE reference_type = 'order'
      AND transaction_type = 'deduct'
      AND status = 1;

COMMENT ON INDEX uq_agent_wallet_order_debit IS '保证每个订单最多存在一条成功扣款流水，软删除不能绕过资金幂等';
