/**
 * POST /api/refresh/studies
 *
 * Manual/cron-triggered revalidation endpoint for the PubMed-backed Studies
 * cache. Intended to be hit by an external scheduler (systemd timer, GitHub
 * Actions cron, Coolify scheduled task) more frequently than the in-memory
 * 6-hour `unstable_cache` revalidate window so the list stays fresh.
 *
 * Auth: shared bearer token in `CRON_SECRET`. If the env var is missing we
 * return 401 by default — failing closed is safer than accepting all traffic.
 *
 * On success we call `revalidateTag("studies", "max")` which marks the
 * cached entry stale with stale-while-revalidate semantics (Next 16's
 * recommended form — the single-arg signature is now deprecated).
 */

import { revalidateTag } from "next/cache";

import { STUDIES_CACHE_TAG } from "@/lib/studies/cache";

export async function POST(request: Request): Promise<Response> {
  const secret = process.env.CRON_SECRET;
  if (!secret) {
    return Response.json(
      { ok: false, error: "CRON_SECRET not configured" },
      { status: 401 },
    );
  }

  const header = request.headers.get("authorization") ?? "";
  const expected = `Bearer ${secret}`;
  if (header !== expected) {
    return Response.json({ ok: false, error: "unauthorized" }, { status: 401 });
  }

  try {
    revalidateTag(STUDIES_CACHE_TAG, "max");
  } catch (err) {
    return Response.json(
      {
        ok: false,
        error: "revalidation failed",
        detail: err instanceof Error ? err.message : String(err),
      },
      { status: 500 },
    );
  }

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