import { sendPendingMailboxPushNotifications } from "@/lib/mail-push";
import { refreshMailboxByEmail } from "@/lib/official-mail";

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

function isAuthorized(request: Request) {
  const expected = process.env.OFFICIAL_MAIL_CRON_SECRET?.trim();
  return Boolean(
    expected && request.headers.get("x-officialmail-cron-secret")?.trim() === expected,
  );
}

export async function POST(request: Request) {
  if (!isAuthorized(request)) {
    return Response.json({ error: "unauthorized" }, { status: 401 });
  }

  let body: { email?: string; reason?: string };

  try {
    body = await request.json();
  } catch {
    return Response.json({ error: "invalid-request" }, { status: 400 });
  }

  const email = String(body.email ?? "").trim().toLowerCase();

  if (!email) {
    return Response.json({ error: "email-required" }, { status: 400 });
  }

  try {
    // Push notifications only need message metadata, but AI relay needs the raw
    // MIME source. Start hydration here as part of the same receipt event so a
    // missed secondary IMAP watcher event cannot leave relay pending until login.
    await refreshMailboxByEmail(email, { folder: "inbox" });
    const result = await sendPendingMailboxPushNotifications(email);
    return Response.json({
      ok: true,
      reason: String(body.reason ?? "manual").slice(0, 80),
      result,
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "mail-push-run-failed";
    console.error(`[mail-push] run failed mailbox=${email} message=${message}`);
    return Response.json({ error: "mail-push-run-failed" }, { status: 500 });
  }
}
