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

import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { env } from "@/lib/env"
import { assertAuthenticatedSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { rowsToCsv } from "@/lib/csv"

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 convexUrl = env.NEXT_PUBLIC_CONVEX_URL
  if (!convexUrl) {
    return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
  }

  const client = new ConvexHttpClient(convexUrl)
  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 backlog CSV", 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 { searchParams } = new URL(request.url)
    const range = searchParams.get("range") ?? undefined
    const companyId = searchParams.get("companyId") ?? undefined
    const report = await client.query(api.reports.backlogOverview, {
      tenantId,
      viewerId: viewerId as unknown as Id<"users">,
      range,
      companyId: companyId as unknown as Id<"companies">,
    })

    const rows: Array<Array<unknown>> = []
    rows.push(["Relatório", "Backlog"])
    rows.push(["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : "—"])
    if (companyId) rows.push(["EmpresaId", companyId])
    rows.push([])
    rows.push(["Seção", "Chave", "Valor"]) // header

    // Status
    const STATUS_PT: Record<string, string> = {
      PENDING: "Pendentes",
      AWAITING_ATTENDANCE: "Aguardando atendimento",
      PAUSED: "Pausados",
      RESOLVED: "Resolvidos",
    }
    for (const [status, total] of Object.entries(report.statusCounts)) {
      rows.push(["Status", STATUS_PT[status] ?? status, total])
    }

    // Prioridade
    const PRIORITY_PT: Record<string, string> = {
      LOW: "Baixa",
      MEDIUM: "Média",
      HIGH: "Alta",
      URGENT: "Crítica",
    }
    for (const [priority, total] of Object.entries(report.priorityCounts)) {
      rows.push(["Prioridade", PRIORITY_PT[priority] ?? priority, total])
    }

    // Filas
    for (const q of report.queueCounts) {
      rows.push(["Fila", q.name || q.id, q.total])
    }

    rows.push(["Abertos", "Total", report.totalOpen])

    const csv = rowsToCsv(rows)
    return new NextResponse(csv, {
      headers: {
        "Content-Type": "text/csv; charset=UTF-8",
        "Content-Disposition": `attachment; filename="backlog-${tenantId}-${report.rangeDays ?? 'all'}d.csv"`,
        "Cache-Control": "no-store",
      },
    })
  } catch (error) {
    console.error("Failed to generate backlog CSV", error)
    return NextResponse.json({ error: "Falha ao gerar CSV do backlog" }, { status: 500 })
  }
}
