import { NextResponse } from "next/server";
import { prisma } from "@nexus/db";
import { sendWeeklyDigest } from "@nexus/api";
import { logger } from "@nexus/api/lib/logger";
import { verifyCronSecret } from "~/lib/cron-auth.js";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

/**
 * GET /api/cron/weekly-digest
 *
 * Sends a weekly capacity digest email to all ADMIN and MANAGER users.
 * Contains team utilization, overbooking count, open demand count, and
 * upcoming vacations for the next 4 weeks.
 *
 * Secure with CRON_SECRET: requests must include `Authorization: Bearer <secret>`.
 * Schedule: run every Monday morning (e.g. `0 7 * * 1` in cron syntax).
 */
export async function GET(request: Request) {
  const deny = verifyCronSecret(request);
  if (deny) return deny;

  try {
    const result = await sendWeeklyDigest(prisma);

    return NextResponse.json({
      ok: true,
      ...result,
      sentAt: new Date().toISOString(),
    });
  } catch (error) {
    logger.error({ error, route: "/api/cron/weekly-digest" }, "Weekly digest cron failed");
    return NextResponse.json({ ok: false, error: "Internal error" }, { status: 500 });
  }
}
