import { NextResponse } from "next/server"

import { assertAuthenticatedSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import type { DeviceInventoryColumnConfig } from "@/lib/device-inventory-columns"
import { buildMachineCategoryWorkbook, 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 machineId = searchParams.get("machineId") ?? undefined
  const userId = searchParams.get("userId") ?? undefined
  const dateFrom = searchParams.get("dateFrom") ?? undefined
  const dateTo = searchParams.get("dateTo") ?? undefined
  const columnsParam = searchParams.get("columns")
  let columns: DeviceInventoryColumnConfig[] | undefined
  if (columnsParam) {
    try {
      const parsed = JSON.parse(columnsParam)
      if (Array.isArray(parsed)) {
        columns = parsed
          .map((item) => {
            if (typeof item === "string") {
              return { key: item }
            }
            if (item && typeof item === "object" && typeof item.key === "string") {
              return {
                key: item.key,
                label: typeof item.label === "string" && item.label.length > 0 ? item.label : undefined,
              }
            }
            return null
          })
          .filter((item): item is DeviceInventoryColumnConfig => item !== null)
      }
    } catch (error) {
      console.warn("Invalid columns parameter for machine category export", error)
    }
  }

  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 buildMachineCategoryWorkbook(context, {
      range,
      companyId: companyId || undefined,
      machineId: machineId || undefined,
      userId: userId || undefined,
      dateFrom,
      dateTo,
      columns,
    })

    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 machine category export", error)
    return NextResponse.json({ error: "Falha ao gerar planilha de máquinas x categorias" }, { status: 500 })
  }
}
