/**
 * POST /api/email-reports/send-now/[id] — trigger an immediate send
 */

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

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

export async function POST(_req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const schedule = await prisma.emailReportSchedule.findUnique({
    where: { id: params.id },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!schedule) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!schedule.brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const result = await generateAndSendReport(schedule.id);
  return NextResponse.json(result);
}
