-- 031_work_order_search.sql —— 扩展接单工单搜索字段并建立模糊检索索引。

CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE INDEX IF NOT EXISTS idx_work_orders_search_text_trgm
  ON work_orders USING gin (
    LOWER(
      COALESCE(work_order_no, '') || ' ' ||
      COALESCE(platform_order_id, '') || ' ' ||
      COALESCE(product_name, '') || ' ' ||
      COALESCE(material_json->'collect'->'fields'->>'gameId', '') || ' ' ||
      COALESCE(material_json->'collect'->'fields'->>'gameNickname', '') || ' ' ||
      COALESCE(material_json->'collect'->'fields'->>'gameAccount', '') || ' ' ||
      COALESCE(material_json->'collect'->'fields'->>'roleName', '') || ' ' ||
      COALESCE(material_json->'fields'->>'gameId', '') || ' ' ||
      COALESCE(material_json->'fields'->>'gameNickname', '') || ' ' ||
      COALESCE(material_json->>'gameId', '') || ' ' ||
      COALESCE(material_json->>'gameNickname', '')
    ) gin_trgm_ops
  );

COMMENT ON INDEX idx_work_orders_search_text_trgm IS '接单工单模糊搜索：订单号、商品名、游戏 ID/昵称及历史字段';
