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"

export const runtime = "nodejs"

function csvEscape(value: unknown): string {
  const s = value == null ? "" : String(value)
  if (/[",\n]/.test(s)) {
    return '"' + s.replace(/"/g, '""') + '"'
  }
  return s
}

function rowsToCsv(rows: Array<Array<unknown>>): string {
  return rows.map((row) => row.map(csvEscape).join(",")).join("\n") + "\n"
}

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 { searchParams } = new URL(request.url)
  const range = searchParams.get("range") ?? undefined
  const companyId = searchParams.get("companyId") ?? undefined

  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 SLA 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 report = await client.query(api.reports.slaOverview, {
      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", "SLA e produtividade"])
    rows.push(["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : (range ?? "90d")])
    if (companyId) rows.push(["EmpresaId", companyId])
    rows.push([])

    rows.push(["Métrica", "Valor"]) // header
    rows.push(["Tickets totais", report.totals.total])
    rows.push(["Tickets abertos", report.totals.open])
    rows.push(["Tickets resolvidos", report.totals.resolved])
    rows.push(["Atrasados (SLA)", report.totals.overdue])
    rows.push([])
    rows.push(["Tempo médio de 1ª resposta (min)", report.response.averageFirstResponseMinutes ?? "—"])
    rows.push(["Respostas registradas", report.response.responsesRegistered ?? 0])
    rows.push(["Tempo médio de resolução (min)", report.resolution.averageResolutionMinutes ?? "—"])
    rows.push(["Tickets resolvidos (amostra)", report.resolution.resolvedCount ?? 0])
    rows.push([])
    rows.push(["Fila", "Abertos"])
    for (const q of report.queueBreakdown ?? []) {
      rows.push([q.name || q.id, q.open])
    }

    const csv = rowsToCsv(rows)
    const daysLabel = (() => {
      const raw = (range ?? "90d").replace("d", "")
      return /^(7|30|90)$/.test(raw) ? `${raw}d` : "all"
    })()
    return new NextResponse(csv, {
      headers: {
        "Content-Type": "text/csv; charset=UTF-8",
        "Content-Disposition": `attachment; filename="sla-${tenantId}-${daysLabel}.csv"`,
        "Cache-Control": "no-store",
      },
    })
  } catch (error) {
    console.error("Failed to generate SLA CSV", error)
    return NextResponse.json({ error: "Falha ao gerar CSV de SLA" }, { status: 500 })
  }
}
