import { NextResponse } from "next/server";
import { createAdminClient } from "@/lib/supabase/admin";

// Cache aggressively — directory rarely changes, and 1k+ companies is ~50KB.
export const revalidate = 600;

export async function GET() {
  try {
    const svc = createAdminClient();
    const { data } = await svc
      .from("tracked_companies")
      .select("company_name, slug")
      .eq("directory_visible", true)
      .not("slug", "is", null)
      .not("company_name", "is", null);

    const rows = (data || [])
      .filter((r: any) => r.company_name && r.slug)
      .map((r: any) => ({ name: String(r.company_name).trim(), slug: String(r.slug) }))
      .filter((r) => r.name.length >= 3);

    return NextResponse.json(
      { companies: rows },
      { headers: { "Cache-Control": "public, s-maxage=600, stale-while-revalidate=1200" } },
    );
  } catch (e: any) {
    return NextResponse.json({ companies: [], error: e?.message || "error" }, { status: 500 });
  }
}
