// app/api/spectacles/route.ts
import { NextResponse, NextRequest } from "next/server";
import { createSbServer } from "@/lib/supabaseServer";

export async function GET(req: NextRequest) {
  try {
    const supabase = createSbServer();
    
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    if (authError || !user) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    const url = new URL(req.url);
    const q = url.searchParams.get("q") || "";
    const page = parseInt(url.searchParams.get("page") || "1");
    const limit = parseInt(url.searchParams.get("limit") || "10");

    console.log("🎭 API spectacles search:", { q, page, limit, user_id: user.id });

    let query = supabase
      .from("productions")
      .select("id,name,reference,prod_type,director")
      .order("name", { ascending: true });

    if (q && q.trim().length > 0) {
      query = query.ilike("name", `%${q.trim()}%`);
    }

    // Pagination
    const from = (page - 1) * limit;
    const to = from + limit - 1;
    query = query.range(from, to);

    const { data, error, count } = await query;
    
    console.log("🎭 API spectacles result:", { 
      data: data?.length, 
      error: error?.message,
      count
    });

    if (error) {
      console.error("spectacles search error:", error.message);
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

    const items = (data || []).map(item => ({
      id: item.id || null,
      nom: item.name || "",
      numero_objet: item.reference || null,
      prod_type: item.prod_type || null,
      director: item.director || null,
    }));

    return NextResponse.json({ 
      items,
      page,
      limit,
      total: count,
      hasMore: data ? data.length === limit : false
    });

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