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

CREATE TABLE IF NOT EXISTS tb_card_wallet_transaction (
    id BIGSERIAL PRIMARY KEY,
    card_wallet_id BIGINT NOT NULL,
    resource_type VARCHAR(20) NOT NULL,
    resource_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_card_tx_status CHECK (status IN (1, 2, 3)),
    CONSTRAINT chk_card_tx_type CHECK (transaction_type IN ('recharge', 'deduct', 'refund'))
);

-- 按钱包查询交易历史索引
CREATE INDEX idx_card_tx_wallet ON tb_card_wallet_transaction (card_wallet_id, created_at DESC);

-- 按资源查询交易索引
CREATE INDEX idx_card_tx_resource ON tb_card_wallet_transaction (resource_type, resource_id, created_at DESC);

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

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

-- 多租户过滤索引
CREATE INDEX idx_card_tx_shop_tag ON tb_card_wallet_transaction (shop_id_tag);

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

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