import { NextResponse } from "next/server";
import { getDbPool } from "@/db";
import { getSession } from "@/lib/auth";
import { buildInspectionReportPdf } from "@/lib/report-pdf";
import { resolveInspectionTenant } from "@/lib/authorization";

export const runtime = "nodejs";

const finalStatuses = ["approved", "approved_with_notes", "rejected"];

export async function GET(request: Request, { params }: { params: Promise<{ externalId: string }> }) {
  try {
    const session = await getSession();
    if (!session) return NextResponse.json({ error: "Faça login para baixar o laudo." }, { status: 401 });
    const { externalId } = await params; const db = getDbPool();
    const isClient = session.role.startsWith("client_"); const tenantId = await resolveInspectionTenant(session, new URL(request.url).searchParams.get("tenantId"));
    if (!tenantId) return NextResponse.json({ error: "Cliente da vistoria não encontrado ou inativo." }, { status: 404 });
    if (isClient) { const [profileRows] = await db.execute("SELECT client_can_download_report FROM tenant_access_profiles WHERE tenant_id = ? LIMIT 1", [tenantId]); if (!Boolean((profileRows as { client_can_download_report?: number }[])[0]?.client_can_download_report)) return NextResponse.json({ error: "O download de laudos não está habilitado para este cliente." }, { status: 403 }); }
    const [inspectionRows] = await db.execute("SELECT * FROM inspections WHERE tenant_id = ? AND external_id = ? LIMIT 1", [tenantId, externalId]); const inspection = (inspectionRows as Record<string, unknown>[])[0];
    if (!inspection) return NextResponse.json({ error: "Vistoria não encontrada." }, { status: 404 });
    if (!finalStatuses.includes(String(inspection.status))) return NextResponse.json({ error: "O laudo estará disponível após uma decisão conclusiva.", hint: "Conclua a análise automática ou humana antes de gerar o PDF." }, { status: 409 });
    const inspectionId = String(inspection.id), cycle = Number(inspection.inspection_cycle || 1);
    const [photos] = await db.execute(`SELECT p.category_code, p.storage_key, p.ai_status, p.ai_quality_score, p.latitude, p.longitude, p.created_at,
      a.summary, a.findings, a.ocr_plate, a.plate_match, a.ocr_chassis, a.chassis_match,
      m.assessment AS manual_assessment, m.damage_location AS manual_damage_location,
      m.comments AS manual_comments, m.analyst_name AS manual_analyst_name, m.updated_at AS manual_updated_at
      FROM inspection_photos p
      LEFT JOIN inspection_photo_analyses a ON a.inspection_photo_id = p.id
      LEFT JOIN inspection_photo_manual_assessments m ON m.inspection_photo_id = p.id
      WHERE p.inspection_id = ? AND p.inspection_cycle = ? AND p.ai_status <> 'retriage' AND COALESCE(a.status, '') <> 'failed'
      ORDER BY p.created_at`, [inspectionId, cycle]);
    const requiredPhotos: Record<string, number> = { light: 8, motorcycle: 6, heavy: 6 };
    if ((photos as unknown[]).length < (requiredPhotos[String(inspection.vehicle_type)] || 99)) return NextResponse.json({ error: "O laudo só pode ser emitido após todas as fotos obrigatórias serem aceitas.", hint: "Há fotos pendentes ou que precisam ser refeitas." }, { status: 409 });
    const [reviewRows] = await db.execute("SELECT analyst_name, decision, comments, reason, completed_at FROM inspection_reviews WHERE inspection_id = ? AND review_status = 'completed' ORDER BY completed_at DESC LIMIT 1", [inspectionId]);
    const [evaluations] = await db.execute("SELECT rule_name, points, action FROM inspection_rule_evaluations WHERE inspection_id = ? ORDER BY points DESC, created_at", [inspectionId]);
    const pdf = await buildInspectionReportPdf({ inspection, review: (reviewRows as Record<string, unknown>[])[0] ?? null, evaluations: evaluations as Record<string, unknown>[], photos: photos as never[] });
    const safeId = String(externalId).replace(/[^a-zA-Z0-9_-]/g, "-");
    return new NextResponse(pdf, { headers: { "Content-Type": "application/pdf", "Content-Disposition": `attachment; filename="laudo-autovistoria-veicular-${safeId}.pdf"`, "Cache-Control": "private, no-store" } });
  } catch (error) { console.error("Erro ao gerar laudo PDF", error); return NextResponse.json({ error: "Não foi possível gerar o laudo em PDF." }, { status: 500 }); }
}
