CREATE TABLE player_services
(
    id           BIGINT PRIMARY KEY,
    player_id    BIGINT         NOT NULL REFERENCES players (id),
    game_id      BIGINT         NOT NULL,
    title        VARCHAR(200)   NOT NULL,
    description  TEXT,
    price        DECIMAL(10, 2) NOT NULL,
    unit         VARCHAR(20)    NOT NULL,
    rank_range   VARCHAR(100),
    availability TEXT[]                  DEFAULT ARRAY []::TEXT[],
    rating       DECIMAL(3, 2)           DEFAULT 5.00,
    is_active    BOOLEAN                 DEFAULT TRUE,
    created_at   TIMESTAMPTZ    NOT NULL DEFAULT NOW(),
    updated_at   TIMESTAMPTZ    NOT NULL DEFAULT NOW(),

    CONSTRAINT chk_price_positive CHECK (price > 0),
    CONSTRAINT chk_service_rating CHECK (rating >= 0 AND rating <= 5)
);

-- 基础索引
CREATE INDEX idx_services_player ON player_services (player_id) WHERE is_active = TRUE;
CREATE INDEX idx_services_game ON player_services (game_id) WHERE is_active = TRUE;
CREATE INDEX idx_services_price ON player_services (price);

-- 三元组索引用于服务标题模糊搜索
CREATE INDEX idx_services_title_trgm ON player_services USING gin (title gin_trgm_ops)
    WHERE is_active = TRUE;

-- 全文搜索索引
CREATE INDEX idx_services_fulltext ON player_services USING gin (
                                                                 to_tsvector('simple', title || ' ' || coalesce(description, ''))
    ) WHERE is_active = TRUE;

-- 复合索引优化价格区间查询
CREATE INDEX idx_services_game_price ON player_services (game_id, price, rating DESC)
    WHERE is_active = TRUE;

-- 打手+游戏复合索引
CREATE INDEX idx_services_player_game ON player_services (player_id, game_id)
    WHERE is_active = TRUE;

-- GIN 索引优化时间段查询
CREATE INDEX idx_services_availability ON player_services USING gin (availability)
    WHERE is_active = TRUE;

CREATE TRIGGER trigger_services_updated_at
    BEFORE UPDATE
    ON player_services
    FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();