/**
 * Search RPC handlers — FTS5 full-text search.
 * Fix #13: Returns typed error for invalid queries.
 */

import type { SearchDb } from "../search-db.ts";

export function createSearchHandlers(searchDb: SearchDb) {
  return {
    "search.query": ({ query, limit }: { query: string; limit?: number }) => {
      try {
        const results = searchDb.searchAll(query, limit ?? 20);
        return { results };
      } catch (err) {
        const error = err instanceof Error ? err.message : String(err);
        console.error("[search.query]", err);
        return { results: [], error };
      }
    },

    "search.indexMessage": ({ sessionId, role, content }: { sessionId: string; role: string; content: string }) => {
      try {
        searchDb.indexMessage(sessionId, role, content);
        return { ok: true };
      } catch (err) {
        console.error("[search.indexMessage]", err);
        return { ok: false };
      }
    },

    "search.rebuild": () => {
      try {
        searchDb.rebuildIndex();
        return { ok: true };
      } catch (err) {
        console.error("[search.rebuild]", err);
        return { ok: false };
      }
    },
  };
}
