// app/api/search/organizations/route.ts
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";

export async function GET(req: Request) {
  try {
    const supabase = createRouteHandlerClient({ cookies });

    const {
      data: { user },
      error: userErr,
    } = await supabase.auth.getUser();
    if (userErr) console.error("supabase.getUser error:", userErr.message);
    if (!user) return new Response("Unauthorized", { status: 401 });

    const url = new URL(req.url);
    const q = url.searchParams.get("q") || "";

    let query = supabase.from("organizations").select("id,name,structure_api").order("name", { ascending: true });
    if (q && q.trim().length > 0) {
      // ilike for case-insensitive match
      query = query.ilike("name", `%${q.trim()}%`);
    }

    const { data, error } = await query;
    if (error) {
      console.error("organizations search error:", error.message);
      return new Response(error.message, { status: 400 });
    }

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