import { NextResponse } from "next/server"

import { assertAuthenticatedSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { buildCategoryInsightsWorkbook, 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 companyId = searchParams.get("companyId") ?? undefined
  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 buildCategoryInsightsWorkbook(context, {
      range,
      companyId: companyId || 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("Failed to generate category insights export", error)
    return NextResponse.json({ error: "Falha ao gerar planilha de categorias" }, { status: 500 })
  }
}
