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

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

export async function GET(request: NextRequest, { params }: { params: Promise<{ reminderId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession()) || !(await hasPermission("invoicing"))) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }

  const { reminderId } = await params;
  await connectDB();
  const reminder = await Reminder.findById(reminderId).lean();
  if (!reminder) return NextResponse.json({ error: "Nicht gefunden." }, { status: 404, headers });
  const invoice = await Invoice.findById(reminder.invoiceId).lean();
  if (!invoice) return NextResponse.json({ error: "Nicht gefunden." }, { status: 404, headers });

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