import { NextResponse } from "next/server"
import { requireUser, isStaff } from "@/server/auth"
import { prisma } from "@/server/db"
import { refreshSubaccountMetricsByIds } from "@/server/subaccount-metrics"
import { cnpjMatches } from "@/server/cnpj"

export async function POST(req: Request) {
  try {
    const user = await requireUser()
    if (isStaff(user.role)) {
      return NextResponse.json({ error: "FORBIDDEN" }, { status: 403 })
    }

    const cnpj = user.cnpj?.trim()
    if (!cnpj) {
      return NextResponse.json({ error: "FORBIDDEN_NO_CNPJ" }, { status: 403 })
    }

    const allMetas = await prisma.subaccountMeta.findMany({
      where: { cnpj: { not: null } },
      select: { subaccountId: true, name: true, cnpj: true },
    })
    const metas = allMetas.filter((m) => cnpjMatches(m.cnpj, cnpj))

    const targets = metas.map((m) => ({ subaccountId: m.subaccountId, name: m.name ?? null }))
    const body = await req.json().catch(() => null)
    const idsFromBody = Array.isArray(body?.subaccountIds)
      ? body.subaccountIds
          .map((id: unknown) => String(id ?? "").trim())
          .filter(Boolean)
      : []
    const targetById = new Map(targets.map((t) => [t.subaccountId, t]))
    const filteredTargets = idsFromBody.length
      ? idsFromBody.map((id: string) => targetById.get(id)).filter(Boolean) as typeof targets
      : targets
    const limit = body?.limit ? Number(body.limit) : undefined

    const result = await refreshSubaccountMetricsByIds(filteredTargets, { limit })
    return NextResponse.json({ ok: true, result })
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : String(e ?? "")
    return NextResponse.json({ error: msg || "METRICS_REFRESH_ERROR" }, { status: 500 })
  }
}
