import { NextResponse } from "next/server"
import { requireStaff } from "@/server/auth"
import { getActiveSmtpPlans } from "@/server/portal-auth"

export async function GET() {
  try {
    await requireStaff()
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : String(e ?? "")
    console.warn("admin/smtp-plans/csv: unauthorized access attempt", msg)
    return NextResponse.json({ error: "UNAUTHORIZED" }, { status: 401 })
  }

  const rows = await getActiveSmtpPlans()
  const map = new Map<string, { cliente: string | null; plano: string; quantidade: number; dominios: Set<string> }>()

  for (const r of rows) {
    const key = `${r.cliente_id}::${r.plano}`
    const existing = map.get(key)
    if (!existing) {
      map.set(key, {
        cliente: r.razao_social ?? null,
        plano: r.plano,
        quantidade: 1,
        dominios: new Set(r.dominio ? [r.dominio] : []),
      })
    } else {
      existing.quantidade += 1
      if (r.dominio) existing.dominios.add(r.dominio)
    }
  }

  const header = ["Cliente", "Plano SMTP", "Quantidade de Pacotes", "Dominios"]
  const lines = [header.join(";")]

  for (const row of map.values()) {
    const dominios = Array.from(row.dominios.values()).join(" | ")
    const values = [
      row.cliente ?? "",
      row.plano,
      String(row.quantidade),
      dominios,
    ].map((v) => `"${String(v).replace(/\"/g, '""')}"`)
    lines.push(values.join(";"))
  }

  const csv = lines.join("\n")
  return new NextResponse(csv, {
    headers: {
      "content-type": "text/csv; charset=utf-8",
      "content-disposition": `attachment; filename=\"planos_smtp_${new Date().toISOString().slice(0, 10)}.csv\"`,
      "cache-control": "no-store",
    },
  })
}
