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

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

  const { rows } = await getUsersPage({ pageSize: 100000, page: 1 })

  const csv = toCsv(
    ["Email", "Name", "Plan", "Status", "Properties", "Tenants", "Joined", "Banned", "Role"],
    rows.map((r) => [
      r.email,
      r.full_name,
      r.plan,
      r.subscription_status,
      r.propertyCount,
      r.tenantCount,
      String(r.created_at).slice(0, 10),
      r.banned ? "yes" : "no",
      r.role,
    ])
  )

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