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"
function msToHours(ms: number) {
  return (ms / 3600000).toFixed(2)
}

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 q = searchParams.get("q")?.toLowerCase().trim() ?? ""
  const companyId = searchParams.get("companyId") ?? ""

  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) {
    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.hoursByClient, {
      tenantId,
      viewerId: viewerId as unknown as Id<"users">,
      range,
    })

    const rows: Array<Array<unknown>> = []
    rows.push(["Relatório", "Horas por cliente"]) 
    rows.push(["Período", report.rangeDays ? `Últimos ${report.rangeDays} dias` : (range ?? '90d')])
    if (q) rows.push(["Filtro", q])
    rows.push([])
    rows.push(["Cliente", "Avulso", "Horas internas", "Horas externas", "Horas totais", "Horas contratadas/mês", "% uso"])
    type Item = { companyId: string; name: string; isAvulso: boolean; internalMs: number; externalMs: number; totalMs: number; contractedHoursPerMonth: number | null }
    let items = (report.items as Item[])
    if (companyId) items = items.filter((i) => String(i.companyId) === companyId)
    if (q) items = items.filter((i) => i.name.toLowerCase().includes(q))
    for (const item of items) {
      const internalH = msToHours(item.internalMs)
      const externalH = msToHours(item.externalMs)
      const totalH = msToHours(item.totalMs)
      const contracted = item.contractedHoursPerMonth ?? "—"
      const pct = item.contractedHoursPerMonth ? ((item.totalMs / 3600000) / item.contractedHoursPerMonth * 100).toFixed(1) + "%" : "—"
      rows.push([item.name, item.isAvulso ? "Sim" : "Não", internalH, externalH, totalH, contracted, pct])
    }
    const csv = rowsToCsv(rows)
    return new NextResponse(csv, {
      headers: {
        "Content-Type": "text/csv; charset=UTF-8",
        "Content-Disposition": `attachment; filename="hours-by-client-${tenantId}-${report.rangeDays ?? '90'}d${companyId ? `-${companyId}` : ''}${q ? `-${encodeURIComponent(q)}` : ''}.csv"`,
        "Cache-Control": "no-store",
      },
    })
  } catch (error) {
    return NextResponse.json({ error: "Falha ao gerar CSV de horas por cliente" }, { status: 500 })
  }
}
