DO $$
BEGIN
    IF EXISTS (
        SELECT 1
          FROM tb_agent_wallet_transaction
         WHERE reference_type IN ('topup', 'manual_adjustment')
           AND transaction_type IN ('recharge', 'adjustment')
           AND status = 1
           AND reference_id IS NOT NULL
         GROUP BY reference_type, reference_id
        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_credit_posting_reference
    ON tb_agent_wallet_transaction (reference_type, reference_id)
    WHERE reference_type IN ('topup', 'manual_adjustment')
      AND transaction_type IN ('recharge', 'adjustment')
      AND status = 1;

COMMENT ON INDEX uq_agent_wallet_credit_posting_reference IS '保证每个充值或人工调整业务引用最多存在一条成功入账流水，软删除不能绕过资金幂等';

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
          FROM tb_agent_recharge_record
         WHERE payment_transaction_id IS NOT NULL
           AND payment_transaction_id <> ''
         GROUP BY payment_channel, payment_transaction_id
        HAVING COUNT(*) > 1
    ) THEN
        RAISE EXCEPTION '存在同一支付渠道重复使用的代理充值第三方交易号，禁止创建唯一索引';
    END IF;
END
$$;

CREATE UNIQUE INDEX uq_agent_recharge_provider_transaction
    ON tb_agent_recharge_record (payment_channel, payment_transaction_id)
    WHERE payment_transaction_id IS NOT NULL
      AND payment_transaction_id <> '';

COMMENT ON INDEX uq_agent_recharge_provider_transaction IS '保证同一支付渠道的第三方交易号最多绑定一张代理充值单';
