import { NextResponse } from "next/server"
import { requireStaff } from "@/server/auth"
import { refreshSubaccountMetrics, refreshSubaccountMetricsByIds } from "@/server/subaccount-metrics"

export async function POST(req: Request) {
  const secret = process.env.CRON_SECRET
  const auth = req.headers.get("authorization") || ""
  const isCron = secret && auth === `Bearer ${secret}`

  if (!isCron) {
    try {
      await requireStaff()
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : String(e ?? "")
      console.warn("admin/subaccounts/metrics/refresh: unauthorized access attempt", msg)
      return NextResponse.json({ error: "UNAUTHORIZED" }, { status: 401 })
    }
  }

  const body = await req.json().catch(() => null)
  const limit = body?.limit ? Number(body.limit) : undefined
  const idsFromBody = Array.isArray(body?.subaccountIds)
    ? body.subaccountIds
        .map((id: unknown) => String(id ?? "").trim())
        .filter(Boolean)
    : []

  try {
    const result = idsFromBody.length
      ? await refreshSubaccountMetricsByIds(
          idsFromBody.map((id: string) => ({ subaccountId: id, name: null })),
          { limit }
        )
      : await refreshSubaccountMetrics({ limit })
    return NextResponse.json({ ok: true, result })
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : String(e ?? "")
    return NextResponse.json({ error: msg || "METRICS_REFRESH_ERROR" }, { status: 500 })
  }
}
