import { NextResponse } from "next/server"
import { ConvexHttpClient } from "convex/browser"

import { api } from "@/convex/_generated/api"
import { assertAuthenticatedSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { buildMachinesInventoryWorkbook, type MachineInventoryRecord } from "@/server/machines/inventory-export"
import type { DeviceInventoryColumnConfig } from "@/lib/device-inventory-columns"
import { requireConvexUrl } from "@/server/convex-client"

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 companyId = searchParams.get("companyId") ?? undefined
  const machineIdParams = searchParams.getAll("machineId").filter(Boolean)
  const machineIdFilter = machineIdParams.length > 0 ? new Set(machineIdParams) : null
  const columnsParam = searchParams.get("columns")
  let columnConfig: DeviceInventoryColumnConfig[] | undefined
  if (columnsParam) {
    try {
      const parsed = JSON.parse(columnsParam)
      if (Array.isArray(parsed)) {
        columnConfig = 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 machines export", error)
    }
  }

  const client = new ConvexHttpClient(requireConvexUrl())
  const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID

  let viewerId: string | null = null
  try {
    const ensuredUser = await client.mutation(api.users.ensureUser, {
      tenantId,
      name: session.user.name ?? session.user.email,
      email: session.user.email,
      avatarUrl: session.user.avatarUrl ?? undefined,
      role: session.user.role.toUpperCase(),
    })
    viewerId = ensuredUser?._id ?? null
  } catch (error) {
    console.error("Failed to synchronize user with Convex for machines export", error)
    return NextResponse.json({ error: "Falha ao sincronizar usuário com Convex" }, { status: 500 })
  }

  if (!viewerId) {
    return NextResponse.json({ error: "Usuário não encontrado no Convex" }, { status: 403 })
  }

  try {
    const machines = (await client.query(api.devices.listByTenant, {
      tenantId,
      includeMetadata: true,
    })) as MachineInventoryRecord[]

    const filtered = machines.filter((machine) => {
      if (companyId) {
        const companyMatches = String(machine.companyId ?? "") === companyId || (machine.companySlug ?? "") === companyId
        if (!companyMatches) {
          return false
        }
      }
      if (machineIdFilter && !machineIdFilter.has(String(machine.id))) {
        return false
      }
      return true
    })
    const companyFilterLabel = (() => {
      if (!companyId) return null
      const matchById = filtered.find((machine) => machine.companyId && String(machine.companyId) === companyId)
      if (matchById?.companyName) return matchById.companyName
      const matchBySlug = filtered.find((machine) => machine.companySlug === companyId)
      if (matchBySlug?.companyName) return matchBySlug.companyName
      return companyId
    })()

    const workbook = buildMachinesInventoryWorkbook(filtered, {
      tenantId,
      generatedBy: session.user.name ?? session.user.email,
      companyFilterLabel,
      generatedAt: new Date(),
      columns: columnConfig,
    })

    const body = new Uint8Array(workbook)

    return new NextResponse(body, {
      headers: {
        "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "Content-Disposition": `attachment; filename="machines-inventory-${tenantId}${companyId ? `-${companyId}` : ""}.xlsx"`,
        "Cache-Control": "no-store",
      },
    })
  } catch (error) {
    console.error("Failed to generate machines inventory export", error)
    return NextResponse.json({ error: "Falha ao gerar planilha de inventário" }, { status: 500 })
  }
}
