import { NextResponse } from "next/server";
import { createClient } from "@supabase/supabase-js";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const SUPABASE_ANON = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
const SCHEMA = process.env.NEXT_PUBLIC_SUPABASE_SCHEMA || "bb";

function client() {
  return createClient(SUPABASE_URL, SUPABASE_ANON, {
    db: { schema: SCHEMA as "public" },
    auth: { persistSession: false },
  });
}

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const q = (searchParams.get("q") || "").trim();
  if (q.length < 2) {
    return NextResponse.json({ items: [] });
  }
  const limit = Math.min(parseInt(searchParams.get("limit") || "8", 10) || 8, 15);
  const like = `%${q.replace(/[%_]/g, " ")}%`;

  const sb = client();
  const { data, error } = await sb
    .from("wp_imported_posts")
    .select("wp_slug, title, category")
    .eq("status", "published")
    .or(`title.ilike.${like},author_name.ilike.${like}`)
    .order("wp_published_at", { ascending: false, nullsFirst: false })
    .limit(limit);

  if (error) {
    return NextResponse.json({ items: [], error: error.message }, { status: 500 });
  }

  const items = (data || []).map((r: any) => ({
    slug: r.wp_slug,
    title: r.title,
    category: r.category,
    href: `/news/${r.wp_slug}`,
  }));

  return NextResponse.json(
    { items, query: q },
    {
      headers: {
        "Cache-Control": "public, s-maxage=30, stale-while-revalidate=60",
      },
    },
  );
}
