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

CREATE TABLE IF NOT EXISTS tb_card_recharge_record (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL,
    card_wallet_id BIGINT NOT NULL,
    resource_type VARCHAR(20) NOT NULL,
    resource_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_card_recharge_amount CHECK (amount >= 100),
    CONSTRAINT chk_card_recharge_status CHECK (status IN (1, 2, 3, 4, 5)),
    CONSTRAINT chk_card_recharge_method CHECK (payment_method IN ('alipay', 'wechat'))
);

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

-- 按资源查询充值记录索引
CREATE INDEX idx_card_recharge_resource ON tb_card_recharge_record (resource_type, resource_id, created_at DESC);

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

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

-- 多租户过滤索引
CREATE INDEX idx_card_recharge_shop_tag ON tb_card_recharge_record (shop_id_tag);

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

-- 添加注释
COMMENT ON TABLE tb_card_recharge_record IS '卡充值记录表';
COMMENT ON COLUMN tb_card_recharge_record.user_id IS '操作人用户 ID';
COMMENT ON COLUMN tb_card_recharge_record.card_wallet_id IS '卡钱包 ID';
COMMENT ON COLUMN tb_card_recharge_record.resource_type IS '资源类型（冗余字段）';
COMMENT ON COLUMN tb_card_recharge_record.resource_id IS '资源 ID（冗余字段）';
COMMENT ON COLUMN tb_card_recharge_record.recharge_no IS '充值订单号（格式：CRCH+时间戳+随机数）';
COMMENT ON COLUMN tb_card_recharge_record.amount IS '充值金额（单位：分，最小 100 分 = 1 元）';
COMMENT ON COLUMN tb_card_recharge_record.payment_method IS '支付方式：alipay-支付宝 | wechat-微信';
COMMENT ON COLUMN tb_card_recharge_record.payment_channel IS '支付渠道';
COMMENT ON COLUMN tb_card_recharge_record.payment_transaction_id IS '第三方支付交易号';
COMMENT ON COLUMN tb_card_recharge_record.status IS '充值状态：1-待支付 2-已支付 3-已完成 4-已关闭 5-已退款';
COMMENT ON COLUMN tb_card_recharge_record.paid_at IS '支付时间';
COMMENT ON COLUMN tb_card_recharge_record.completed_at IS '完成时间';
