-- 创建代理充值记录表
-- 记录所有代理充值操作

CREATE TABLE IF NOT EXISTS tb_agent_recharge_record (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL,
    agent_wallet_id BIGINT NOT NULL,
    shop_id BIGINT NOT NULL,
    recharge_no VARCHAR(50) NOT NULL UNIQUE,
    amount BIGINT NOT NULL,
    payment_method VARCHAR(20) NOT NULL,
    payment_channel VARCHAR(50),
    payment_transaction_id VARCHAR(100),
    status INT NOT NULL DEFAULT 1,
    paid_at TIMESTAMP,
    completed_at TIMESTAMP,
    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_recharge_amount CHECK (amount >= 10000),
    CONSTRAINT chk_agent_recharge_status CHECK (status IN (1, 2, 3, 4, 5)),
    CONSTRAINT chk_agent_recharge_method CHECK (payment_method IN ('alipay', 'wechat', 'bank', 'offline'))
);

-- 按用户查询充值记录索引
CREATE INDEX idx_agent_recharge_user ON tb_agent_recharge_record (user_id, created_at DESC);

-- 按店铺查询充值记录索引
CREATE INDEX idx_agent_recharge_shop ON tb_agent_recharge_record (shop_id, created_at DESC);

-- 按状态过滤充值记录索引
CREATE INDEX idx_agent_recharge_status ON tb_agent_recharge_record (status, created_at DESC);

-- 按订单号查询索引
CREATE UNIQUE INDEX idx_agent_recharge_no ON tb_agent_recharge_record (recharge_no);

-- 多租户过滤索引
CREATE INDEX idx_agent_recharge_shop_tag ON tb_agent_recharge_record (shop_id_tag);

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

-- 添加注释
COMMENT ON TABLE tb_agent_recharge_record IS '代理充值记录表';
COMMENT ON COLUMN tb_agent_recharge_record.user_id IS '操作人用户 ID';
COMMENT ON COLUMN tb_agent_recharge_record.agent_wallet_id IS '代理钱包 ID';
COMMENT ON COLUMN tb_agent_recharge_record.shop_id IS '店铺 ID（冗余字段，便于查询）';
COMMENT ON COLUMN tb_agent_recharge_record.recharge_no IS '充值订单号（格式：ARCH+时间戳+随机数）';
COMMENT ON COLUMN tb_agent_recharge_record.amount IS '充值金额（单位：分，最小 10000 分 = 100 元）';
COMMENT ON COLUMN tb_agent_recharge_record.payment_method IS '支付方式：alipay-支付宝 | wechat-微信 | bank-银行转账 | offline-线下';
COMMENT ON COLUMN tb_agent_recharge_record.payment_channel IS '支付渠道';
COMMENT ON COLUMN tb_agent_recharge_record.payment_transaction_id IS '第三方支付交易号';
COMMENT ON COLUMN tb_agent_recharge_record.status IS '充值状态：1-待支付 2-已支付 3-已完成 4-已关闭 5-已退款';
COMMENT ON COLUMN tb_agent_recharge_record.paid_at IS '支付时间';
COMMENT ON COLUMN tb_agent_recharge_record.completed_at IS '完成时间';
