import { revalidateTag } from "next/cache";

import { NEWS_CACHE_TAG } from "@/lib/news/cache";

/**
 * Manual / cron-triggered news refresh endpoint.
 *
 * Expected usage:
 *   curl -X POST https://orthoglobe.org/api/refresh/news \
 *     -H "Authorization: Bearer $CRON_SECRET"
 *
 * Auth: shared-secret Bearer token compared to `process.env.CRON_SECRET`.
 * We intentionally do NOT add this to the zod-validated env schema — the
 * news refresh is a best-effort operational concern, and we want the
 * endpoint to fail closed (503) when no secret is configured rather than
 * crashing the whole app on boot.
 *
 * Behaviour:
 *   - Missing/empty `CRON_SECRET` env => 503 so operators notice.
 *   - Wrong / missing Authorization header => 401.
 *   - Success => `revalidateTag("news", "max")` which marks the cache
 *     entry stale; next page visit will trigger a background refetch.
 */
export async function POST(request: Request) {
  const secret = process.env.CRON_SECRET;
  if (!secret) {
    return Response.json(
      { error: "CRON_SECRET not configured" },
      { status: 503 },
    );
  }

  const header = request.headers.get("authorization") || "";
  const match = /^Bearer\s+(.+)$/i.exec(header.trim());
  const provided = match ? match[1].trim() : "";
  if (!provided || provided !== secret) {
    return Response.json({ error: "unauthorized" }, { status: 401 });
  }

  try {
    // "max" = stale-while-revalidate semantics per Next 16 docs.
    revalidateTag(NEWS_CACHE_TAG, "max");
  } catch (error) {
    console.warn("[api/refresh/news] revalidateTag threw", error);
    return Response.json(
      { error: "revalidation failed" },
      { status: 500 },
    );
  }

  return Response.json({
    ok: true,
    tag: NEWS_CACHE_TAG,
    at: new Date().toISOString(),
  });
}
