import { NextResponse } from "next/server";
import { prisma } from "@capakraken/db";
import { checkChargeabilityAlerts } from "@capakraken/api";

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

/**
 * GET /api/cron/chargeability-alerts
 *
 * Finds resources whose current-month chargeability is >15 percentage points
 * below their target and creates in-app notifications for managers.
 *
 * Duplicate-safe: only one alert per resource per month.
 *
 * Optionally protect with CRON_SECRET environment variable.
 * When set, requests must include `Authorization: Bearer <secret>`.
 */
export async function GET(request: Request) {
  const cronSecret = process.env["CRON_SECRET"];
  if (cronSecret) {
    const auth = request.headers.get("authorization");
    if (auth !== `Bearer ${cronSecret}`) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
  }

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

    return NextResponse.json({
      ok: true,
      alertsSent,
      checkedAt: new Date().toISOString(),
    });
  } catch (error) {
    console.error("[cron/chargeability-alerts] Error:", error);
    return NextResponse.json(
      { ok: false, error: "Internal error" },
      { status: 500 },
    );
  }
}
