// app/api/search/productions/route.ts
import { NextResponse } from "next/server";
import { createSbServer } from "@/lib/supabaseServer";

export async function GET(req: Request) {
  try {
    const supabase = createSbServer();

    const {
      data: { user },
      error: userErr,
    } = await supabase.auth.getUser();
    if (userErr) console.error("supabase.getUser error:", userErr.message);
    if (!user) return NextResponse.json({ error: "Non authentifié" }, { status: 401 });

    const url = new URL(req.url);
    const q = url.searchParams.get("q") || "";
    console.log("🎭 API productions search:", { q, user_id: user.id });

    let query = supabase.from("spectacles").select("id,nom,numero_objet,titre").order("nom", { ascending: true });
    if (q && q.trim().length > 0) {
      query = query.ilike("nom", `%${q.trim()}%`);
    }

    const { data, error } = await query;
    console.log("🎭 API productions result:", { data: data?.length, error: error?.message });
    if (error) {
      console.error("productions search error:", error.message);
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

    return NextResponse.json({ items: data ?? [] });
  } catch (e: any) {
    console.error("/api/search/productions fatal:", e?.message || e);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
