import { NextResponse } from "next/server"
import { getAdminSession } from "@/lib/session"
import { getPlanDistribution, computeMrr, toCsv } from "@/lib/db/admin-queries"

export async function GET() {
  const admin = await getAdminSession()
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 })

  const dist = await getPlanDistribution()
  const { mrr } = computeMrr(dist)

  const csv = toCsv(
    ["Plan", "Subscribers", "Unit Price", "Monthly Contribution"],
    [
      ["starter", dist.starter, 0, 0],
      ["pro", dist.pro, 29, 29 * dist.pro],
      ["landlord", dist.landlord, 59, 59 * dist.landlord],
      ["lifetime", dist.lifetime, 199, "one-time"],
      ["TOTAL MRR", "", "", mrr],
    ]
  )

  return new NextResponse(csv, {
    headers: {
      "Content-Type": "text/csv; charset=utf-8",
      "Content-Disposition": 'attachment; filename="billing.csv"',
      "Cache-Control": "no-store",
    },
  })
}
