import { NextRequest, NextResponse } from "next/server";
import { connectDB } from "@/lib/db";
import { Reminder } from "@/models/Reminder";
import { Invoice } from "@/models/Invoice";
import { getSessionClientId } from "@/lib/auth";
import { hasPermission } from "@/lib/adminAuth";
import { renderReminderPdf } from "@/lib/reminderPdf";

export async function GET(_req: NextRequest, { params }: { params: Promise<{ reminderId: string }> }) {
  const { reminderId } = await params;
  const [clientId, isAdmin] = await Promise.all([getSessionClientId(), hasPermission("invoicing")]);
  if (!clientId && !isAdmin) return new NextResponse("Unauthorized", { status: 401 });

  await connectDB();
  const reminder = await Reminder.findById(reminderId).lean();
  if (!reminder || (!isAdmin && String(reminder.clientId) !== clientId)) {
    return new NextResponse("Not found", { status: 404 });
  }

  const invoice = await Invoice.findById(reminder.invoiceId).lean();
  if (!invoice) return new NextResponse("Not found", { status: 404 });

  const buffer = await renderReminderPdf(reminder, invoice);
  return new NextResponse(new Uint8Array(buffer), {
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": `inline; filename="mahnung-${invoice.number}-${reminder.level}.pdf"`,
      "Cache-Control": "private, max-age=0, no-store",
    },
  });
}
