import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/db";

export async function GET(request: NextRequest) {
  const q = request.nextUrl.searchParams.get("q")?.trim();
  if (!q || q.length < 2) {
    return NextResponse.json([]);
  }

  const db = getDb();
  const like = `%${q}%`;

  const groupRows = db.prepare(
    "SELECT id, name, phone, instagram, telegram, status, notes, created_at, group_info FROM group_bookings WHERE name LIKE ? OR phone LIKE ? ORDER BY created_at DESC LIMIT 20"
  ).all(like, like) as { id: number; name: string; phone: string; instagram: string | null; telegram: string | null; status: string; notes: string | null; created_at: string; group_info: string | null }[];

  const mcRows = db.prepare(
    "SELECT id, name, phone, instagram, telegram, status, notes, created_at, master_class_title FROM mc_registrations WHERE name LIKE ? OR phone LIKE ? ORDER BY created_at DESC LIMIT 20"
  ).all(like, like) as { id: number; name: string; phone: string | null; instagram: string; telegram: string | null; status: string; notes: string | null; created_at: string; master_class_title: string }[];

  const odRows = db.prepare(
    "SELECT id, name, phone, instagram, telegram, status, notes, created_at FROM open_day_bookings WHERE name LIKE ? OR phone LIKE ? ORDER BY created_at DESC LIMIT 20"
  ).all(like, like) as { id: number; name: string; phone: string; instagram: string | null; telegram: string | null; status: string; notes: string | null; created_at: string }[];

  const results = [
    ...groupRows.map((r) => ({
      type: "class" as const,
      id: r.id,
      name: r.name,
      phone: r.phone,
      instagram: r.instagram ?? undefined,
      telegram: r.telegram ?? undefined,
      status: r.status || "new",
      notes: r.notes ?? undefined,
      createdAt: r.created_at,
      groupLabel: r.group_info ?? undefined,
    })),
    ...mcRows.map((r) => ({
      type: "mc" as const,
      id: r.id,
      name: r.name,
      phone: r.phone ?? undefined,
      instagram: r.instagram ?? undefined,
      telegram: r.telegram ?? undefined,
      status: r.status || "new",
      notes: r.notes ?? undefined,
      createdAt: r.created_at,
      groupLabel: r.master_class_title,
    })),
    ...odRows.map((r) => ({
      type: "open-day" as const,
      id: r.id,
      name: r.name,
      phone: r.phone,
      instagram: r.instagram ?? undefined,
      telegram: r.telegram ?? undefined,
      status: r.status || "new",
      notes: r.notes ?? undefined,
      createdAt: r.created_at,
    })),
  ];

  return NextResponse.json(results.slice(0, 50));
}
