import { NextResponse } from "next/server";
import { requireFamily } from "@/lib/auth";
import { getStorageInfo, formatBytes } from "@/lib/quota";

// GET /api/storage-usage — returns storage stats for the UI meter.
// RLS-safe: requireFamily() scopes the query to the authenticated family.
export async function GET() {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const info = await getStorageInfo(familyId);

  return NextResponse.json({
    usedBytes: info.usedBytes,
    limitBytes: info.isPaid ? null : info.limitBytes,
    usedFormatted: formatBytes(info.usedBytes),
    limitFormatted: info.isPaid ? "Unlimited" : formatBytes(info.limitBytes),
    fraction: info.isPaid ? 0 : info.fraction,
    approaching: info.approaching,
    exceeded: info.exceeded,
    isPaid: info.isPaid,
  });
}
