import { all, first } from "../db";
import { forbidden, notFoundError } from "../errors";
import type { Viewer } from "~/lib/types";
export type BillingAccount = { accountId: string; name: string; kind: "user" | "org"; canEdit: boolean };
/** The account whose usage `viewer` may see: themselves, or an org they belong to (owners may edit). */
export async function billingAccountFor(viewer: Viewer, org: string | null): Promise<BillingAccount> {
if (!org) return { accountId: viewer.id, name: viewer.name, kind: "user", canEdit: true };
const account = await first<{ id: string; name: string }>(
"SELECT id, name FROM accounts WHERE name = ? COLLATE NOCASE AND kind = 'org'",
org,
);
if (!account) throw notFoundError("Organization not found");
const member = await first<{ role: string }>(
"SELECT role FROM org_members WHERE org_id = ? AND user_id = ?",
account.id,
viewer.id,
);
if (!member && !viewer.isAdmin) throw notFoundError("Organization not found");
return { accountId: account.id, name: account.name, kind: "org", canEdit: member?.role === "owner" };
}
export function requireSiteAdmin(viewer: Viewer): void {
if (!viewer.isAdmin) throw forbidden("Site administrators only");
}
export type AdminUsageRow = {
accountId: string;
name: string | null;
kind: string | null;
meter: string;
quantity: number;
};
const TOP_PER_METER = 20;
/** Site-admin view: the heaviest accounts for each meter this period (counters and gauge peaks). */
export async function topUsage(period: string): Promise<AdminUsageRow[]> {
const rows = await all<{