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

export async function GET(
  _req: Request,
  context: { params: Promise<{ subaccountId: string }> }
) {
  const { subaccountId } = await context.params
  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 meta = await prisma.subaccountMeta.findUnique({
    where: { subaccountId },
  })
  if (!meta || !cnpjMatches(meta.cnpj, cnpj)) {
    return NextResponse.json({ error: "FORBIDDEN" }, { status: 403 })
  }

  try {
    const keys = await viewApiKeys({ subaccount_id: subaccountId })
    const apiKey = keys.find((k) => k.api_key)?.api_key
    if (!apiKey) {
      return NextResponse.json({ error: "SUBACCOUNT_API_KEY_NOT_FOUND" }, { status: 404 })
    }
    const data = await emailBounces({}, { apiKey })
    return NextResponse.json({ data })
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : String(e ?? "")
    return NextResponse.json({ error: msg || "SMTP2GO_ERROR" }, { status: 500 })
  }
}
