import { NextRequest, NextResponse } from 'next/server';
import { auditAction } from '@/features/foundation/audit-log/service';
import {
  generateApprovedQuotationPdf,
  getStoredApprovedQuotationPdf
} from '@/features/foundation/pdf-generator/server/service';
import { getQuotationDetail } from '@/features/crm/quotations/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, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationPdfDownload
    });
    const pdf = await getStoredApprovedQuotationPdf(id, organization.id, {
      userId: session.user.id,
      auditDownload: true
    });

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

export async function POST(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmQuotationPdfGenerateApproved
    });
    const before = await getQuotationDetail(id, organization.id);
    const pdf = await generateApprovedQuotationPdf(id, organization.id, session.user.id);
    const after = await getQuotationDetail(id, organization.id);

    await auditAction({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_quotation_pdf_generate_approved',
      entityId: id,
      action: 'generate_approved',
      beforeData: before,
      afterData: {
        approvedArtifactId: after.approvedArtifactId,
        approvedPdfUrl: after.approvedPdfUrl,
        approvedTemplateVersionId: after.approvedTemplateVersionId
      }
    });

    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 approved PDF' }, { status: 500 });
  }
}
