import { NextResponse } from "next/server";
import { access, constants, mkdir } from "node:fs/promises";
import path from "node:path";
import { checkSmtp, countRecentMailFailures } from "@/lib/email";

export const dynamic = "force-dynamic";

/* Machine-readable tripwire for uptime monitors. Zero PII, GET only.
   200 always (site alive) — monitors must alert on status:"degraded". */
export async function GET() {
  const started = Date.now();

  // Lead store must be writable — otherwise successful forms lose data.
  let leads: "ok" | "fail" = "fail";
  try {
    const dir = path.join(process.cwd(), "data");
    await mkdir(dir, { recursive: true });
    await access(dir, constants.W_OK);
    leads = "ok";
  } catch {
    leads = "fail";
  }

  const smtp = await checkSmtp();
  const mailFailures24h = await countRecentMailFailures();

  const degraded = smtp === "fail" || leads === "fail" || mailFailures24h > 0;
  return NextResponse.json(
    {
      status: degraded ? "degraded" : "ok",
      uptime: Math.round(process.uptime()),
      ms: Date.now() - started,
      checks: { site: "ok" as const, smtp, leads, mailFailures24h },
    },
    { status: 200, headers: { "cache-control": "no-store" } }
  );
}

export async function POST() {
  return NextResponse.json({ error: "Method not allowed" }, { status: 405 });
}
