import { NextResponse } from "next/server";
import { runReminders } from "@/lib/reminders/runner";

/**
 * Reminder cron endpoint.
 *
 * Called by host cron on the LXC every hour:
 *   curl -fsS -H "Authorization: Bearer $CRON_SECRET" \
 *        -X POST http://localhost:3000/api/cron/reminders
 *
 * Auth: shared-secret bearer. CRON_SECRET must be set in .env.prod.
 *       Without it, the route 503s (refuse to run) so we don't accidentally
 *       expose a public unauthenticated mailer.
 */
export const dynamic = "force-dynamic";
export const runtime = "nodejs";

export async function POST(req: Request) {
  const secret = process.env.CRON_SECRET?.trim();
  if (!secret) {
    return NextResponse.json({ error: "CRON_SECRET not configured" }, { status: 503 });
  }

  const auth = req.headers.get("authorization") ?? "";
  const expected = `Bearer ${secret}`;
  if (auth !== expected) {
    return NextResponse.json({ error: "unauthorized" }, { status: 401 });
  }

  const started = Date.now();
  try {
    const result = await runReminders();
    return NextResponse.json({
      ok: true,
      durationMs: Date.now() - started,
      ...result,
    });
  } catch (e) {
    return NextResponse.json(
      {
        ok: false,
        error: e instanceof Error ? e.message : String(e),
        durationMs: Date.now() - started,
      },
      { status: 500 }
    );
  }
}

// GET helps host cron uptime checks confirm the route exists without firing.
export function GET() {
  return NextResponse.json({
    ok: true,
    hint: "POST with Authorization: Bearer <CRON_SECRET> to run reminders",
  });
}
