import { NextResponse } from "next/server"
import { requireStaff } from "@/server/auth"
import { prisma } from "@/server/db"

const BOUNCE_WARN = 8
const BOUNCE_BAD = 12
const SPAM_WARN = 0.1
const SPAM_BAD = 0.2

function parseNumber(value: string | null, fallback: number) {
  if (!value) return fallback
  const n = Number(value)
  return Number.isFinite(n) ? n : fallback
}

function bounceRating(bounce: number | null) {
  if (bounce === null) return "unknown"
  if (bounce < BOUNCE_WARN) return "good"
  if (bounce < BOUNCE_BAD) return "fair"
  return "poor"
}

function spamRating(spam: number | null) {
  if (spam === null) return "unknown"
  if (spam < SPAM_WARN) return "good"
  if (spam < SPAM_BAD) return "fair"
  return "poor"
}

function csvEscape(value: unknown) {
  const str = value === null || value === undefined ? "" : String(value)
  if (/[",\n]/.test(str)) return `"${str.replace(/"/g, '""')}"`
  return str
}

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

  const url = new URL(req.url)
  const bounceMin = parseNumber(url.searchParams.get("bounce_min"), BOUNCE_WARN)
  const spamMin = parseNumber(url.searchParams.get("spam_min"), SPAM_WARN)

  const rows = await prisma.subaccountMetric.findMany({
    orderBy: { fetchedAt: "desc" },
  })

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

  const filtered = Array.from(latest.values()).filter((row) => {
    const bounce = row.bouncePercent ?? null
    const spam = row.spamPercent ?? null
    return (bounce !== null && bounce >= bounceMin) || (spam !== null && spam >= spamMin)
  })

  const header = [
    "subaccount_id",
    "name",
    "bounce_percent",
    "bounce_rating",
    "spam_percent",
    "spam_rating",
    "emails",
    "rejects",
    "softbounces",
    "hardbounces",
    "cycle_start",
    "cycle_end",
    "cycle_used",
    "cycle_remaining",
    "cycle_max",
    "fetched_at",
  ]

  const lines = [
    header.join(","),
    ...filtered.map((row) => {
      const values = [
        row.subaccountId,
        row.name ?? "",
        row.bouncePercent ?? "",
        bounceRating(row.bouncePercent ?? null),
        row.spamPercent ?? "",
        spamRating(row.spamPercent ?? null),
        row.emails ?? "",
        row.rejects ?? "",
        row.softbounces ?? "",
        row.hardbounces ?? "",
        row.cycleStart ? row.cycleStart.toISOString() : "",
        row.cycleEnd ? row.cycleEnd.toISOString() : "",
        row.cycleUsed ?? "",
        row.cycleRemaining ?? "",
        row.cycleMax ?? "",
        row.fetchedAt.toISOString(),
      ]
      return values.map(csvEscape).join(",")
    }),
  ]

  const csv = lines.join("\n")
  const filename = `subaccounts_report_${new Date().toISOString().slice(0, 10)}.csv`

  return new NextResponse(csv, {
    status: 200,
    headers: {
      "content-type": "text/csv; charset=utf-8",
      "content-disposition": `attachment; filename="${filename}"`,
    },
  })
}
