CREATE TABLE wallet_transactions
(
    id            BIGINT PRIMARY KEY,
    user_id       BIGINT         NOT NULL,
    type          VARCHAR(20)    NOT NULL,
    amount        DECIMAL(12, 2) NOT NULL,
    balance_after DECIMAL(12, 2) NOT NULL,
    description   VARCHAR(500)   NOT NULL,
    order_id      BIGINT,
    created_at    TIMESTAMPTZ    NOT NULL DEFAULT NOW(),
    search_text   TEXT GENERATED ALWAYS AS (
        type || ' ' || description
        ) STORED,

    CONSTRAINT chk_transaction_type CHECK (type IN ('topup', 'payment', 'income', 'withdrawal', 'refund'))
);

-- 基础索引
CREATE INDEX idx_transactions_user ON wallet_transactions (user_id, created_at DESC);
CREATE INDEX idx_transactions_order ON wallet_transactions (order_id) WHERE order_id IS NOT NULL;
CREATE INDEX idx_transactions_type ON wallet_transactions (user_id, type, created_at DESC);

-- 三元组索引用于交易描述搜索
CREATE INDEX idx_transactions_search_trgm ON wallet_transactions USING gin(search_text gin_trgm_ops);

-- 复合索引优化用户交易查询
CREATE INDEX idx_transactions_user_type_created ON wallet_transactions (user_id, type, created_at DESC);

-- 时间范围索引 (用于统计)
CREATE INDEX idx_transactions_created_amount ON wallet_transactions (created_at DESC, amount);

-- 订单关联索引
CREATE INDEX idx_transactions_order_type ON wallet_transactions (order_id, type) WHERE order_id IS NOT NULL;