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

export const runtime = "nodejs";
export const revalidate = 300;

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 },
  });
}

// Slug → list of author_name values that should match. Multiple entries
// are OR'd so name variants ("Ryan Salazar", "Ryan", etc.) all resolve
// to the same author profile.
const SLUG_TO_NAMES: Record<string, string[]> = {
  "ryan-salazar": ["Ryan Salazar"],
  "james-whitfield": ["James Whitfield"],
  "sarah-chen": ["Sarah Chen"],
  "elena-vasquez": ["Elena Vasquez"],
  "marcus-rivera": ["Marcus Rivera"],
  "rachel-kim": ["Rachel Kim"],
  "carlos-mendez": ["Carlos Mendez"],
};

function namesForSlug(slug: string): string[] {
  if (SLUG_TO_NAMES[slug]) return SLUG_TO_NAMES[slug];
  // Fallback: convert "first-last" → "First Last"
  const guess = slug
    .split("-")
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(" ");
  return [guess];
}

export async function GET(
  req: Request,
  { params }: { params: Promise<{ slug: string }> },
) {
  const { slug } = await params;
  const { searchParams } = new URL(req.url);
  const limit = Math.min(parseInt(searchParams.get("limit") || "500", 10) || 500, 5000);

  const names = namesForSlug(slug);
  const sb = client();

  // Count first (for accurate article-count badge)
  const { count: total } = await sb
    .from("wp_imported_posts")
    .select("wp_id", { count: "exact", head: true })
    .eq("status", "published")
    .in("author_name", names);

  const { data } = await sb
    .from("wp_imported_posts")
    .select("wp_id, wp_slug, title, excerpt, category, featured_image, wp_published_at, author_name")
    .eq("status", "published")
    .in("author_name", names)
    .order("wp_published_at", { ascending: false, nullsFirst: false })
    .limit(limit);

  const articles = (data || []).map((r: any) => ({
    slug: r.wp_slug,
    title: r.title,
    excerpt: r.excerpt || "",
    category: r.category || "News",
    date: r.wp_published_at
      ? new Date(r.wp_published_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
      : "",
    image: r.featured_image,
    alt: r.title,
    readTime: estimateReadTime(r.excerpt || ""),
  }));

  return NextResponse.json(
    { slug, names, total: total ?? articles.length, articles },
    { headers: { "Cache-Control": "public, s-maxage=300, stale-while-revalidate=600" } },
  );
}

function estimateReadTime(text: string): string {
  const words = (text || "").trim().split(/\s+/).filter(Boolean).length;
  const minutes = Math.max(1, Math.round((words || 200) / 200));
  return `${minutes} min read`;
}
