import { notFound } from 'next/navigation';
import { renderToBuffer } from '@react-pdf/renderer';
import { getLead } from '@/db/queries';
import { getTenantPerfil } from '@/db/tenant-queries';
import { TIPO_LABEL } from '@/lib/funnel';
import { PresupuestoDoc } from '@/lib/pdf/PresupuestoDoc';
import { construirDescripcionRender, resolverImagenPdf } from '@/lib/pdf/render-info';
import type { BudgetResult } from '@/budget/types';
import type { AbstractedPreferences } from '@/lib/voice/preferences';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function GET(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const data = await getLead(id);
  if (!data) notFound();

  const descargar = new URL(req.url).searchParams.get('download') === '1';

  const { lead } = data;
  const empresa = await getTenantPerfil();

  const snapshot = lead.desgloseSnapshot as { result: BudgetResult } | null;
  const desglose = snapshot?.result ?? null;

  const [logoSrc, imagenSrc] = await Promise.all([
    resolverImagenPdf(empresa.logoUrl, { formato: 'png', maxAncho: 400 }),
    resolverImagenPdf(lead.renderUrl, { formato: 'jpeg', maxAncho: 1400 }),
  ]);
  const prefs = lead.preferencesSnapshot as AbstractedPreferences | null;
  const render = imagenSrc
    ? {
        imagenSrc,
        descripcion: construirDescripcionRender({
          calidad: lead.calidadGlobal,
          materiales: desglose?.materialesRender ?? [],
          estilo: prefs?.estiloRender ?? [],
        }),
      }
    : null;

  const buffer = await renderToBuffer(
    PresupuestoDoc({
      empresa,
      cliente: { nombre: lead.nombre, telefono: lead.telefono, provincia: lead.provincia },
      reforma: {
        tipoLabel: lead.tipoReforma ? TIPO_LABEL[lead.tipoReforma] : 'Reforma',
        fecha: lead.createdAt,
      },
      desglose,
      logoSrc,
      render,
    })
  );

  const slug = lead.nombre.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
  return new Response(new Uint8Array(buffer), {
    headers: {
      'Content-Type': 'application/pdf',
      'Content-Disposition': `${descargar ? 'attachment' : 'inline'}; filename="presupuesto-${slug || lead.id}.pdf"`,
      'Cache-Control': 'no-store',
    },
  });
}
