import { NextRequest, NextResponse } from 'next/server';
import { generateAssembledQuotationPdf } from '@/features/foundation/document-assembly/server/service';
import {
  auditCrmSecurityEvent,
  buildCrmSecurityContext,
  canViewQuotationPricing,
} from '@/features/crm/security/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

export async function POST(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess(
      { permission: PERMISSIONS.crmQuotationPdfDownload },
    );
    const securityContext = buildCrmSecurityContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership,
    });

    if (!canViewQuotationPricing(securityContext)) {
      await auditCrmSecurityEvent({
        organizationId: organization.id,
        userId: session.user.id,
        action: 'pricing_hidden',
        entityType: 'crm_quotation',
        entityId: id,
        reason: 'Assembled quotation PDF generation requires pricing visibility',
      });
      return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
    }

    const assembled = await generateAssembledQuotationPdf(
      id,
      organization.id,
      session.user.id,
    );

    return NextResponse.json({
      success: true,
      fileName: assembled.fileName,
      checksum: assembled.checksum,
      fileSize: assembled.fileSize,
      pageCount: assembled.pageCount,
      warnings: assembled.warnings,
      artifact: assembled.artifact,
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json(
      { message: 'Unable to generate assembled quotation PDF' },
      { status: 500 },
    );
  }
}
