/**
 * External Status Check — Cron-triggered batch endpoint.
 *
 * N8N cron: POST with Bearer token, 4x/day (9, 12, 15, 17) weekdays.
 * ?test=true for dry-run (check but don't save/email).
 */

import { NextResponse } from "next/server";
import { runStatusCheck } from "@/modules/registratura/services/status-check-service";

const CRON_SECRET =
  process.env.STATUS_CHECK_CRON_SECRET ??
  process.env.NOTIFICATION_CRON_SECRET;

export async function POST(request: Request) {
  if (!CRON_SECRET) {
    return NextResponse.json(
      { error: "STATUS_CHECK_CRON_SECRET not configured" },
      { status: 500 },
    );
  }

  const authHeader = request.headers.get("Authorization");
  const token = authHeader?.replace("Bearer ", "");

  if (token !== CRON_SECRET) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const url = new URL(request.url);
  const dryRun = url.searchParams.get("test") === "true";

  const result = await runStatusCheck(dryRun);

  return NextResponse.json(result, {
    status: result.success ? 200 : 500,
  });
}
