/**
 * GET /api/cron/email-reports — sends all due email reports.
 * Protected by CRON_SECRET.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { generateAndSendReport } from "@/lib/services/email-report-generator";

export const dynamic = "force-dynamic";
export const maxDuration = 300;

const CRON_SECRET = process.env.CRON_SECRET ?? "";

function authOk(req: Request): boolean {
  if (!CRON_SECRET) return false;
  const header = req.headers.get("authorization") ?? "";
  if (header === `Bearer ${CRON_SECRET}`) return true;
  return new URL(req.url).searchParams.get("secret") === CRON_SECRET;
}

export async function GET(req: Request) {
  if (!authOk(req)) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const due = await prisma.emailReportSchedule.findMany({
    where: { isActive: true, nextSendAt: { lte: new Date() } },
    select: { id: true, name: true, brandId: true },
    take: 50,
  });

  const results: Array<{ id: string; name: string; success: boolean; error?: string }> = [];

  for (const schedule of due) {
    try {
      const result = await generateAndSendReport(schedule.id);
      results.push({ id: schedule.id, name: schedule.name, success: result.success, error: result.error });
    } catch (err) {
      results.push({ id: schedule.id, name: schedule.name, success: false, error: err instanceof Error ? err.message : "Unknown error" });
    }
  }

  return NextResponse.json({ processed: results.length, results });
}
