-- 创建代理钱包交易记录表
-- 记录所有代理钱包余额变动

CREATE TABLE IF NOT EXISTS tb_agent_wallet_transaction (
    id BIGSERIAL PRIMARY KEY,
    agent_wallet_id BIGINT NOT NULL,
    shop_id BIGINT NOT NULL,
    user_id BIGINT NOT NULL,
    transaction_type VARCHAR(20) NOT NULL,
    amount BIGINT NOT NULL,
    balance_before BIGINT NOT NULL,
    balance_after BIGINT NOT NULL,
    status INT NOT NULL DEFAULT 1,
    reference_type VARCHAR(50),
    reference_id BIGINT,
    remark TEXT,
    metadata JSONB,
    creator BIGINT NOT NULL,
    shop_id_tag BIGINT NOT NULL,
    enterprise_id_tag BIGINT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP,

    -- 约束
    CONSTRAINT chk_agent_tx_status CHECK (status IN (1, 2, 3)),
    CONSTRAINT chk_agent_tx_type CHECK (transaction_type IN ('recharge', 'deduct', 'refund', 'commission', 'withdrawal'))
);

-- 按钱包查询交易历史索引
CREATE INDEX idx_agent_tx_wallet ON tb_agent_wallet_transaction (agent_wallet_id, created_at DESC);

-- 按店铺汇总交易索引
CREATE INDEX idx_agent_tx_shop ON tb_agent_wallet_transaction (shop_id, created_at DESC);

-- 按关联业务查询索引
CREATE INDEX idx_agent_tx_ref ON tb_agent_wallet_transaction (reference_type, reference_id) WHERE reference_type IS NOT NULL;

-- 按交易类型统计索引
CREATE INDEX idx_agent_tx_type ON tb_agent_wallet_transaction (transaction_type, created_at DESC);

-- 多租户过滤索引
CREATE INDEX idx_agent_tx_shop_tag ON tb_agent_wallet_transaction (shop_id_tag);

-- 企业标签索引
CREATE INDEX idx_agent_tx_enterprise_tag ON tb_agent_wallet_transaction (enterprise_id_tag) WHERE enterprise_id_tag IS NOT NULL;

-- 添加注释
COMMENT ON TABLE tb_agent_wallet_transaction IS '代理钱包交易记录表';
COMMENT ON COLUMN tb_agent_wallet_transaction.agent_wallet_id IS '代理钱包 ID';
COMMENT ON COLUMN tb_agent_wallet_transaction.shop_id IS '店铺 ID（冗余字段，便于查询）';
COMMENT ON COLUMN tb_agent_wallet_transaction.user_id IS '操作人用户 ID';
COMMENT ON COLUMN tb_agent_wallet_transaction.transaction_type IS '交易类型：recharge-充值 | deduct-扣款 | refund-退款 | commission-分佣 | withdrawal-提现';
COMMENT ON COLUMN tb_agent_wallet_transaction.amount IS '变动金额（单位：分，正数为增加，负数为减少）';
COMMENT ON COLUMN tb_agent_wallet_transaction.balance_before IS '变动前余额（单位：分）';
COMMENT ON COLUMN tb_agent_wallet_transaction.balance_after IS '变动后余额（单位：分）';
COMMENT ON COLUMN tb_agent_wallet_transaction.status IS '交易状态：1-成功 2-失败 3-处理中';
COMMENT ON COLUMN tb_agent_wallet_transaction.reference_type IS '关联业务类型（如 order | commission | withdrawal | topup）';
COMMENT ON COLUMN tb_agent_wallet_transaction.reference_id IS '关联业务 ID';
COMMENT ON COLUMN tb_agent_wallet_transaction.metadata IS '扩展信息（如手续费、支付方式等）';
