import { z } from 'zod';
import * as kbQ from '@/server/db/queries/support-kb.js';
import type { SupportTool, ToolResult } from './_types.js';
import type { AgentDeps } from '../types.js';

const inputSchema = z.object({
  query: z.string().min(1).max(500),
  locale: z.enum(['he', 'en']),
});

type Output = Array<{ slug: string; title: string; snippet: string }>;

async function impl(deps: AgentDeps, rawInput: unknown): Promise<ToolResult<Output>> {
  const parsed = inputSchema.safeParse(rawInput);
  if (!parsed.success) return { ok: false, error: `INVALID_INPUT:${parsed.error.message}` };

  const rows = await kbQ.search(deps.db, parsed.data.query, parsed.data.locale, 'public');

  return {
    ok: true,
    data: rows.slice(0, 5).map((r) => ({
      slug: r.slug,
      title: r.title,
      snippet: r.bodyMd.slice(0, 300),
    })),
  };
}

export const searchKbTool = {
  name: 'search_kb',
  inputSchema,
  impl,
} satisfies SupportTool<'search_kb', z.infer<typeof inputSchema>, Output>;
