import { NextResponse } from "next/server";
import { getLatestImportedArticles } from "@/lib/articles/legacy-source";

export const revalidate = 300;

const MAX_LIMIT = 200;
const DEFAULT_LIMIT = 100;

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const limit = Math.min(
    Math.max(parseInt(searchParams.get("limit") || `${DEFAULT_LIMIT}`, 10) || DEFAULT_LIMIT, 1),
    MAX_LIMIT,
  );
  const page = Math.max(parseInt(searchParams.get("page") || "0", 10) || 0, 0);
  const offset = page * limit;

  const { items, total } = await getLatestImportedArticles(limit, offset);

  const payload = items.map((a) => ({
    title: a.title,
    excerpt: a.excerpt,
    category: a.category,
    date: a.date,
    author: a.author,
    authorSlug: a.authorSlug,
    slug: a.slug,
    image: a.image,
    alt: a.alt,
    source: "imported" as const,
  }));

  return NextResponse.json(
    {
      items: payload,
      page,
      limit,
      total,
      pages: Math.ceil(total / limit),
    },
    {
      headers: {
        "Cache-Control": "public, s-maxage=300, stale-while-revalidate=600",
      },
    },
  );
}
