import { NextResponse } from "next/server"
import { getSession } from "@/server/session"
import { prisma } from "@/server/db"
import { searchSubaccounts } from "@/server/smtp2go"
import { cnpjMatches } from "@/server/cnpj"

export async function GET() {
  const session = await getSession()
  const user = session.user

  if (!user) {
    return NextResponse.json({ error: "UNAUTHORIZED" }, { status: 401 })
  }

  if (user.role === "ADMIN" || user.role === "SUPPORT") {
    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 } },
  })
  const metas = allMetas.filter((m) => cnpjMatches(m.cnpj, cnpj))

  const stateById = new Map<string, string | null>()
  let token: string | undefined
  do {
    const page = await searchSubaccounts({
      fuzzy_search: true,
      states: "all",
      sort_direction: "asc",
      page_size: 100,
      continue_token: token,
    })
    const list = page?.subaccounts ?? []
    for (const sa of list) {
      const sid = String(sa.subaccount_id ?? sa.subaccountId ?? sa.id ?? "").trim()
      if (!sid) continue
      stateById.set(sid, typeof sa.state === "string" ? sa.state : null)
    }
    token = page?.continue_token || page?.continueToken || undefined
  } while (token)

  const metrics = metas.length
    ? await prisma.subaccountMetric.findMany({
        where: { subaccountId: { in: metas.map((m) => m.subaccountId) } },
        orderBy: { fetchedAt: "desc" },
      })
    : []

  const metricMap = new Map<string, (typeof metrics)[number]>()
  for (const m of metrics) {
    if (!metricMap.has(m.subaccountId)) {
      metricMap.set(m.subaccountId, m)
    }
  }

  const subaccounts = metas.map((m) => {
    const metric = metricMap.get(m.subaccountId)
    return {
      subaccountId: m.subaccountId,
      name: m.name ?? null,
      state: stateById.get(m.subaccountId) ?? null,
      cnpj: m.cnpj ?? null,
      domain: m.domain ?? null,
      dkimVerified: m.dkimVerified ?? null,
      rpathVerified: m.rpathVerified ?? null,
      dkimSelector: m.dkimSelector ?? null,
      rpathSelector: m.rpathSelector ?? null,
      domainCheckedAt: m.domainCheckedAt ?? null,
      metricEmailCount: metric?.emails ?? null,
      metricCycleUsed: metric?.cycleUsed ?? null,
      metricCycleMax: metric?.cycleMax ?? null,
      metricFetchedAt: metric?.fetchedAt ?? null,
    }
  })

  return NextResponse.json({ subaccounts })
}
