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

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

/**
 * GET /api/cron/estimate-reminders
 *
 * Scans for estimates that have been in SUBMITTED status for more than 3 days
 * without approval and creates in-app reminder notifications for managers.
 *
 * Intended to be called by an external cron job (e.g. `curl http://host/api/cron/estimate-reminders`)
 * or a scheduled task runner.
 *
 * Optionally protect this endpoint with a shared secret via the `CRON_SECRET`
 * environment variable. When set, requests must include the header
 * `Authorization: Bearer <secret>`.
 */
export async function GET(request: Request) {
  const deny = verifyCronSecret(request);
  if (deny) return deny;

  try {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const reminderCount = await checkPendingEstimateReminders(prisma as any);

    return NextResponse.json({
      ok: true,
      remindersCreated: reminderCount,
      checkedAt: new Date().toISOString(),
    });
  } catch (error) {
    logger.error({ error, route: "/api/cron/estimate-reminders" }, "Estimate reminder cron failed");
    return NextResponse.json(
      { ok: false, error: "Internal error" },
      { status: 500 },
    );
  }
}
