// app/api/search/salaries/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("salaries").select("code_salarie,prenom,nom,adresse_mail").order("nom", { ascending: true }).limit(10);
    if (q && q.trim().length > 0) {
      query = query.ilike("nom", `%${q.trim()}%`).or(`code_salarie.ilike.%${q.trim()}%`).or(`prenom.ilike.%${q.trim()}%`);
    }

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

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