import type { NextApiRequest, NextApiResponse } from "next";
import { getSitemapEntries } from "@/lib/siteUrls";
import { submitUrlsToIndexNow } from "@/lib/indexNow";

// Triggers an IndexNow submission to Bing.
// - No body / no `urls`: resubmits every URL currently in the sitemap.
// - POST { "urls": ["https://send.mn/blog/my-post"] }: submits just those
//   (e.g. call this from a Webflow "Collection Item Published" webhook).
// Set INDEXNOW_ADMIN_SECRET and send it as `x-indexnow-secret` to restrict
// who can trigger submissions once this is wired into a webhook/cron.
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "GET" && req.method !== "POST") {
    res.setHeader("Allow", "GET, POST");
    return res.status(405).json({ error: "Method not allowed" });
  }

  const requiredSecret = process.env.INDEXNOW_ADMIN_SECRET;
  if (requiredSecret && req.headers["x-indexnow-secret"] !== requiredSecret) {
    return res.status(401).json({ error: "Unauthorized" });
  }

  try {
    const body = req.method === "POST" ? req.body : null;
    const explicitUrls: string[] | undefined = Array.isArray(body?.urls)
      ? body.urls.filter((u: unknown): u is string => typeof u === "string")
      : undefined;

    const urls = explicitUrls ?? (await getSitemapEntries()).map((e) => e.loc);
    const result = await submitUrlsToIndexNow(urls);

    return res.status(result.ok ? 200 : 502).json(result);
  } catch (err) {
    console.error("IndexNow submit error:", err);
    return res.status(500).json({ error: "Failed to submit to IndexNow" });
  }
}
