import { NextResponse } from "next/server"
import { isStaff, requireTenantAccess } from "@/server/auth"
import { getTenantSmtp2goSubaccountId } from "@/server/tenant"
import { emailBounces, viewApiKeys } from "@/server/smtp2go"

export async function GET(
  _req: Request,
  context: { params: Promise<{ tenantId: string }> }
) {
  const { tenantId } = await context.params

  try {
    const user = await requireTenantAccess(tenantId)
    const url = new URL(_req.url)
    let subaccount_id = url.searchParams.get("subaccount_id") ?? undefined

    if (subaccount_id) {
      if (!isStaff(user.role)) {
        return NextResponse.json({ error: "FORBIDDEN" }, { status: 403 })
      }
    } else if (isStaff(user.role)) {
      const data = await emailBounces({})
      return NextResponse.json({ data })
    } else {
      subaccount_id = await getTenantSmtp2goSubaccountId(tenantId)
    }
    if (subaccount_id && isStaff(user.role)) {
      const keys = await viewApiKeys({ subaccount_id })
      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 })
    }

    const data = await emailBounces({ subaccount_id })

    return NextResponse.json({ data })
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : String(e ?? "")

    if (msg === "TENANT_MISSING_SUBACCOUNT_ID") {
      return NextResponse.json({ error: "Tenant não possui subconta vinculada.", code: "TENANT_MISSING_SUBACCOUNT_ID" }, { status: 422 })
    }

    const status =
      msg === "UNAUTHORIZED" ? 401 :
      msg.startsWith("FORBIDDEN") ? 403 :
      500

    return NextResponse.json({ error: msg }, { status })
  }
}
