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

import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { assertAuthenticatedSession } from "@/lib/auth-server"
import { mapTicketWithDetailsFromServer } from "@/lib/mappers/ticket"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { renderTicketPdfBuffer } from "@/server/pdf/ticket-pdf-template"
import { requireConvexUrl } from "@/server/convex-client"

export const runtime = "nodejs"

async function readLogoAsDataUrl() {
  const logoPath = path.join(process.cwd(), "public", "logo-raven.png")
  try {
    const buffer = await fs.promises.readFile(logoPath)
    const base64 = buffer.toString("base64")
    return `data:image/png;base64,${base64}`
  } catch (error) {
    console.warn("[tickets.export.pdf] Logo não encontrado, seguindo sem imagem", error)
    return null
  }
}

export async function GET(_request: Request, context: { params: Promise<{ id: string }> }) {
  const { id: ticketId } = await context.params
  const session = await assertAuthenticatedSession()
  if (!session) {
    return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
  }

  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("[tickets.export.pdf] Falha ao sincronizar usuário no Convex", error)
    return NextResponse.json({ error: "Não foi possível preparar a exportação" }, { status: 500 })
  }

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

  let ticketRaw: unknown
  try {
    ticketRaw = await client.query(api.tickets.getById, {
      tenantId,
      id: ticketId as unknown as Id<"tickets">,
      viewerId: viewerId as unknown as Id<"users">,
    })
  } catch (error) {
    console.error("[tickets.export.pdf] Falha ao carregar ticket", error, { tenantId, ticketId, viewerId })
    return NextResponse.json({ error: "Não foi possível carregar o ticket" }, { status: 500 })
  }

  if (!ticketRaw) {
    return NextResponse.json({ error: "Ticket não encontrado" }, { status: 404 })
  }

  const ticket = mapTicketWithDetailsFromServer(ticketRaw)

  const logoDataUrl = await readLogoAsDataUrl()
  try {
    const pdfBuffer = await renderTicketPdfBuffer({ ticket, logoDataUrl })
    const payload = pdfBuffer instanceof Uint8Array ? pdfBuffer : new Uint8Array(pdfBuffer)
    return new NextResponse(payload as unknown as BodyInit, {
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="ticket-${ticket.reference}.pdf"`,
        "Cache-Control": "no-store",
      },
    })
  } catch (error) {
    console.error("[tickets.export.pdf] Falha ao renderizar PDF", error)
    return NextResponse.json({ error: "Não foi possível gerar o PDF" }, { status: 500 })
  }
}
