import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";

/**
 * GET /api/cron/publish-scheduled
 *
 * Promotes articles whose status is "scheduled" and whose scheduledFor is
 * in the past to status="published" (setting publishedAt to now if missing).
 *
 * Auth: simple shared-secret header `x-cron-secret` matching the
 * `cron.secret` setting. Anyone can call without the secret only if no
 * secret is configured (dev convenience). Designed to be invoked by an
 * external scheduler (host cron, GitHub Actions, etc.) every 5 minutes.
 */
export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  // Optional shared secret
  const expected = await prisma.setting
    .findUnique({ where: { key: "cron.secret" }, select: { value: true } })
    .then((r) => r?.value?.trim() ?? "");
  if (expected) {
    const got = req.headers.get("x-cron-secret") ?? "";
    if (got !== expected) {
      return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
    }
  }

  const now = new Date();
  const due = await prisma.article.findMany({
    where: {
      status: "scheduled",
      scheduledFor: { lte: now },
    },
    select: { id: true, slug: true, title: true, scheduledFor: true },
    take: 50,
  });

  let promoted = 0;
  for (const a of due) {
    await prisma.article.update({
      where: { id: a.id },
      data: {
        status: "published",
        publishedAt: a.scheduledFor ?? now,
      },
    });
    await prisma.auditLog.create({
      data: {
        actorId: null,
        actorName: null,
        actorEmail: null,
        source: "system",
        action: "article.scheduled_publish",
        target: a.id,
        meta: { slug: a.slug, title: a.title } as never,
      },
    });
    promoted++;
  }

  return NextResponse.json(
    {
      ok: true,
      promoted,
      checkedAt: now.toISOString(),
      items: due.map((d) => d.slug),
    },
    {
      headers: { "cache-control": "no-store" },
    },
  );
}
