const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000";

export interface MemoryResult {
  id: string;
  url: string;
  thumbnailUrl: string | null;
  visionCaption: string | null;
  visionTags: string[] | null;
  createdAt: string;
}

export interface MemorySearchAnswer {
  text: string;
  memories: MemoryResult[];
}

export async function answerMemoryQuery(
  query: string,
  childId: string | null,
  sessionCookie: string
): Promise<MemorySearchAnswer> {
  try {
    const res = await fetch(`${BASE_URL}/api/memories/search`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Cookie": sessionCookie,
      },
      body: JSON.stringify({ query, childId, limit: 6 }),
    });

    if (!res.ok) throw new Error(`Search HTTP ${res.status}`);

    const data = await res.json();
    const memories: MemoryResult[] = data.items || [];

    if (memories.length === 0) {
      return { text: `I couldn't find any photos matching "${query}". Try a different description.`, memories: [] };
    }

    const captions = memories
      .filter(m => m.visionCaption)
      .slice(0, 3)
      .map(m => `"${m.visionCaption}"`)
      .join(", ");

    const text = `Found ${memories.length} photo${memories.length > 1 ? "s" : ""} matching "${query}".${captions ? ` ${captions}` : ""}`;
    return { text, memories };
  } catch (e) {
    console.error("[memory-search] error:", e);
    return { text: "I couldn't search photos right now. Please try again.", memories: [] };
  }
}
