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

type Row = {
  clienteId: string
  razaoSocial: string | null
  plano: string
  quantidade: number
  dominios: string[]
}

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

  const rows = await getActiveSmtpPlans()
  const map = new Map<string, Row>()

  for (const r of rows) {
    const key = `${r.cliente_id}::${r.plano}`
    const existing = map.get(key)
    if (!existing) {
      map.set(key, {
        clienteId: r.cliente_id,
        razaoSocial: r.razao_social ?? null,
        plano: r.plano,
        quantidade: 1,
        dominios: r.dominio ? [r.dominio] : [],
      })
    } else {
      existing.quantidade += 1
      if (r.dominio && !existing.dominios.includes(r.dominio)) {
        existing.dominios.push(r.dominio)
      }
    }
  }

  return NextResponse.json({ items: Array.from(map.values()) })
}
