import { NextResponse } from "next/server" import { assertAuthenticatedSession } from "@/lib/auth-server" import { DEFAULT_TENANT_ID } from "@/lib/constants" import { buildHoursWorkbook, createConvexContext } from "@/server/report-exporters" export const runtime = "nodejs" export async function GET(request: Request) { const session = await assertAuthenticatedSession() if (!session) return NextResponse.json({ error: "Não autorizado" }, { status: 401 }) const { searchParams } = new URL(request.url) const range = searchParams.get("range") ?? undefined const q = searchParams.get("q")?.toLowerCase().trim() ?? "" const companyId = searchParams.get("companyId") ?? "" const dateFrom = searchParams.get("dateFrom") ?? undefined const dateTo = searchParams.get("dateTo") ?? undefined const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID try { const context = await createConvexContext({ tenantId, name: session.user.name ?? session.user.email, email: session.user.email, avatarUrl: session.user.avatarUrl, role: session.user.role.toUpperCase(), }) const artifact = await buildHoursWorkbook(context, { range, companyId: companyId || undefined, search: q || undefined, dateFrom, dateTo, }) return new NextResponse(artifact.buffer, { headers: { "Content-Type": artifact.mimeType, "Content-Disposition": `attachment; filename="${artifact.fileName}"`, "Cache-Control": "no-store", }, }) } catch (error) { console.error("Falha ao gerar planilha de horas por cliente", error) return NextResponse.json({ error: "Falha ao gerar planilha de horas por cliente" }, { status: 500 }) } }