DO $$
BEGIN
    IF EXISTS (
        SELECT 1
          FROM tb_agent_wallet
         WHERE deleted_at IS NULL
           AND wallet_type = 'main'
           AND frozen_balance > 0
    ) THEN
        RAISE EXCEPTION '存在无法关联稳定业务引用的历史主钱包冻结金额，禁止自动切换统一冻结能力';
    END IF;
    IF EXISTS (
        SELECT 1
          FROM tb_order
         WHERE deleted_at IS NULL
           AND buyer_type = 'agent'
           AND payment_method = 'wallet'
           AND payment_status = 1
    ) THEN
        RAISE EXCEPTION '存在缺少预占事实的历史待支付代理钱包订单，禁止自动切换统一冻结能力';
    END IF;
END
$$;

CREATE TABLE tb_agent_wallet_reservation (
    id BIGSERIAL PRIMARY KEY,
    agent_wallet_id BIGINT NOT NULL,
    shop_id BIGINT NOT NULL,
    amount BIGINT NOT NULL,
    status INT NOT NULL DEFAULT 1,
    reference_type VARCHAR(50) NOT NULL,
    reference_id BIGINT NOT NULL,
    creator BIGINT NOT NULL DEFAULT 0,
    completed_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    shop_id_tag BIGINT NOT NULL,
    enterprise_id_tag BIGINT,
    CONSTRAINT ck_agent_wallet_reservation_amount CHECK (amount > 0),
    CONSTRAINT ck_agent_wallet_reservation_status CHECK (status IN (1, 2, 3)),
    CONSTRAINT uq_agent_wallet_reservation_reference UNIQUE (reference_type, reference_id)
);

COMMENT ON TABLE tb_agent_wallet_reservation IS '代理主钱包资金预占事实表';
COMMENT ON COLUMN tb_agent_wallet_reservation.id IS '预占事实ID';
COMMENT ON COLUMN tb_agent_wallet_reservation.agent_wallet_id IS '代理主钱包ID（无外键）';
COMMENT ON COLUMN tb_agent_wallet_reservation.shop_id IS '钱包所属店铺ID';
COMMENT ON COLUMN tb_agent_wallet_reservation.amount IS '预占金额（单位：分）';
COMMENT ON COLUMN tb_agent_wallet_reservation.status IS '预占状态：1-已冻结 2-已释放 3-已完成扣除';
COMMENT ON COLUMN tb_agent_wallet_reservation.reference_type IS '稳定业务引用类型';
COMMENT ON COLUMN tb_agent_wallet_reservation.reference_id IS '稳定业务引用ID';
COMMENT ON COLUMN tb_agent_wallet_reservation.creator IS '创建人账号ID';
COMMENT ON COLUMN tb_agent_wallet_reservation.completed_at IS '释放或完成扣除时间';
COMMENT ON COLUMN tb_agent_wallet_reservation.created_at IS '创建时间';
COMMENT ON COLUMN tb_agent_wallet_reservation.updated_at IS '更新时间';
COMMENT ON COLUMN tb_agent_wallet_reservation.shop_id_tag IS '店铺数据权限标签';
COMMENT ON COLUMN tb_agent_wallet_reservation.enterprise_id_tag IS '企业数据权限标签';

CREATE INDEX idx_agent_wallet_reservation_wallet ON tb_agent_wallet_reservation (agent_wallet_id, created_at DESC);
CREATE INDEX idx_agent_wallet_reservation_shop ON tb_agent_wallet_reservation (shop_id, created_at DESC);
CREATE INDEX idx_agent_wallet_reservation_status ON tb_agent_wallet_reservation (status, created_at ASC);

COMMENT ON INDEX idx_agent_wallet_reservation_wallet IS '按钱包查询预占事实';
COMMENT ON INDEX idx_agent_wallet_reservation_shop IS '按店铺查询预占事实';
COMMENT ON INDEX idx_agent_wallet_reservation_status IS '按预占状态扫描待处理事实';
