import { NextResponse } from "next/server";
import { runDigest } from "@/core/notifications";
import { sendTestDigest } from "@/core/notifications/notification-service";

/**
 * POST /api/notifications/digest
 *
 * Server-to-server endpoint called by N8N cron.
 * Auth via Authorization: Bearer <NOTIFICATION_CRON_SECRET>
 *
 * Query params:
 *   ?test=true — send a test email with sample data to all subscribers
 */
export async function POST(request: Request) {
  const secret = process.env.NOTIFICATION_CRON_SECRET;

  if (!secret) {
    return NextResponse.json(
      { error: "NOTIFICATION_CRON_SECRET not configured" },
      { status: 500 },
    );
  }

  const authHeader = request.headers.get("Authorization");
  const token = authHeader?.replace("Bearer ", "");

  if (token !== secret) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const url = new URL(request.url);
  const isTest = url.searchParams.get("test") === "true";

  const result = isTest ? await sendTestDigest() : await runDigest();

  return NextResponse.json(result, {
    status: result.success ? 200 : 500,
  });
}
