/**
 * GET /api/email-reports/history?brandId=X&page=1&pageSize=20
 * Lists sent reports for a brand (paginated).
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

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

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

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

  const page = Math.max(1, Number(searchParams.get("page") || 1));
  const pageSize = Math.max(1, Math.min(50, Number(searchParams.get("pageSize") || 20)));
  const skip = (page - 1) * pageSize;

  const [reports, total] = await Promise.all([
    prisma.sentEmailReport.findMany({
      where: { brandId },
      orderBy: { sentAt: "desc" },
      select: { id: true, subject: true, recipients: true, status: true, error: true, sentAt: true, scheduleId: true },
      skip,
      take: pageSize,
    }),
    prisma.sentEmailReport.count({ where: { brandId } }),
  ]);

  return NextResponse.json({ reports, total, page, pageSize, pages: Math.ceil(total / pageSize) });
}
