import { NextRequest, NextResponse } from "next/server";
import { getUSHolidaysForYear, USHoliday } from "@/lib/us-holidays";

// GET /api/us-holidays?years=2026,2027
// Proxy for https://date.nager.at/api/v3/PublicHolidays/{year}/US so the browser
// never calls the third-party API directly (no CORS issues, cached on the server).
export async function GET(req: NextRequest) {
  const yearsParam = req.nextUrl.searchParams.get("years") ?? req.nextUrl.searchParams.get("year");
  if (!yearsParam) {
    return NextResponse.json({ error: "years query param is required" }, { status: 400 });
  }

  const years = Array.from(
    new Set(
      yearsParam
        .split(",")
        .map((y) => Number(y.trim()))
        .filter((y) => Number.isInteger(y) && y >= 1970 && y <= 2100)
    )
  ).slice(0, 6);

  if (!years.length) {
    return NextResponse.json({ error: "No valid years provided" }, { status: 400 });
  }

  try {
    const lists = await Promise.all(years.map((y) => getUSHolidaysForYear(y)));
    const data: USHoliday[] = lists.flat();
    return NextResponse.json({ data });
  } catch {
    return NextResponse.json({ error: "Could not load US holidays" }, { status: 502 });
  }
}