import { NextRequest, NextResponse } from "next/server";
import { searchEvents } from "@/lib/chronicle-db";

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const q = searchParams.get("q")?.trim();
    if (!q) {
      return NextResponse.json({ error: "Missing query parameter q" }, { status: 400 });
    }

    const limit = Math.min(parseInt(searchParams.get("limit") ?? "50"), 200);
    const events = searchEvents(q, limit);

    // Group results by date for easier rendering
    const byDate = new Map<string, typeof events>();
    for (const e of events) {
      if (!byDate.has(e.date)) byDate.set(e.date, []);
      byDate.get(e.date)!.push(e);
    }

    const grouped = Array.from(byDate.entries())
      .sort(([a], [b]) => b.localeCompare(a))
      .map(([date, evts]) => ({ date, events: evts }));

    return NextResponse.json({ results: grouped, total: events.length });
  } catch (err) {
    console.error("[chronicle/search]", err);
    return NextResponse.json({ error: "Search failed" }, { status: 500 });
  }
}
