CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE INDEX IF NOT EXISTS idx_orders_admin_search_text_trgm
  ON orders USING GIN ((
    platform_order_id || ' ' || shop_id || ' ' || shop_name || ' ' ||
    buyer_id || ' ' || buyer_name || ' ' || receiver_contact
  ) gin_trgm_ops);

CREATE INDEX IF NOT EXISTS idx_order_items_admin_search_text_trgm
  ON order_items USING GIN ((
    sku_code || ' ' || sku_name || ' ' ||
    COALESCE(item_snapshot_json->'kuaishouSendCode'->>'itemTitle', '') || ' ' ||
    COALESCE(item_snapshot_json->'kuaishouSendCode'->>'skuNick', '')
  ) gin_trgm_ops);

CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_status_order
  ON fulfillment_tasks(task_status, order_id);

CREATE INDEX IF NOT EXISTS idx_fulfillment_tasks_executor_order
  ON fulfillment_tasks(executor_key, order_id);

COMMENT ON INDEX idx_orders_admin_search_text_trgm IS
  '支持后台订单号、店铺、买家及联系方式综合模糊搜索';
COMMENT ON INDEX idx_order_items_admin_search_text_trgm IS
  '支持后台订单商品名、SKU、快手商品标题和 SKU 标题综合模糊搜索';
COMMENT ON INDEX idx_fulfillment_tasks_status_order IS
  '支持后台按任务状态筛选订单';
COMMENT ON INDEX idx_fulfillment_tasks_executor_order IS
  '支持后台按履约渠道筛选订单';
