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

// Lowered from 300 → 60 so the promoted-story sort reflects current
// advertiser state within a minute of a campaign flip.
export const revalidate = 60;

const MAX_LIMIT = 10000;
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 base = 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,
  }));

  // Decorate with promotion badges; preserve wp_published_at order.
  const decorated = await decorateHomepageFeed("avbeat", base);
  const payload = decorated.map((d) => ({
    ...d.article,
    promoted_kind: d.promoted_kind,
    promoted_advertiser: d.promoted_advertiser || null,
    promoted_until: d.promoted_until || null,
  }));

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