import { NextRequest, NextResponse } from 'next/server';
import { generateQuotationPdf } from '@/features/foundation/pdf-generator/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = {
  params: Promise<{ id: string }>;
};

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationPdfDownload
    });
    const pdf = await generateQuotationPdf(id, organization.id);

    return new NextResponse(pdf.buffer, {
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': `attachment; filename="${pdf.fileName}"`
      }
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }
    return NextResponse.json({ message: 'Unable to generate quotation PDF' }, { status: 500 });
  }
}
