import type { DataGridColumn } from "@/components/common/DataGrid.vue";
import type { AdminBillingUserSummary, AdminUsageRow, UsageLedgerRow } from "@/types";

export const userColumns: DataGridColumn[] = [
  { key: "user", label: "User" },
  { key: "status", label: "Status" },
  { key: "credits", label: "Credits", align: "right" },
  { key: "usage", label: "Usage", align: "right" },
  { key: "keys", label: "Keys", align: "right" },
  { key: "actions", label: "Action", align: "right" },
];

export const usageColumns: DataGridColumn[] = [
  { key: "time", label: "Time" },
  { key: "user", label: "User" },
  { key: "service", label: "Service" },
  { key: "resource", label: "Resource" },
  { key: "credits", label: "Credits", align: "right" },
  { key: "status", label: "Status" },
  { key: "metadata", label: "Metadata" },
];

export const ledgerColumns: DataGridColumn[] = [
  { key: "time", label: "Time" },
  { key: "user", label: "User" },
  { key: "action", label: "Action" },
  { key: "delta", label: "Delta", align: "right" },
  { key: "balance", label: "Before/After", align: "right" },
  { key: "operator", label: "Operator" },
  { key: "idempotency", label: "Idempotency" },
];

export function userKey(item: AdminBillingUserSummary): string {
  return item.user?.id ?? item.user?.username ?? "unknown-user";
}
export function auditKey(item: AdminUsageRow | UsageLedgerRow): string {
  return item.id ?? `${item.userId ?? "user"}:${item.createdAt ?? "time"}`;
}
export function formatNumber(value: unknown): string {
  const number = Number(value ?? 0);
  return Number.isFinite(number) ? new Intl.NumberFormat("zh-CN").format(number) : "0";
}
export function formatSigned(value: unknown): string {
  const number = Number(value ?? 0);
  return `${number > 0 ? "+" : ""}${formatNumber(number)}`;
}
export function formatDate(value: unknown): string {
  const text = String(value ?? "");
  if (!text) return "-";
  const date = new Date(text);
  return Number.isNaN(date.getTime()) ? text : date.toLocaleString("zh-CN");
}
export function metadataPreview(value: unknown): string {
  if (!value || typeof value !== "object" || Array.isArray(value)) return "-";
  return Object.entries(value as Record<string, unknown>)
    .slice(0, 4)
    .map(([key, item]) => `${key}=${typeof item === "object" ? "[structured]" : String(item)}`)
    .join(" · ") || "-";
}
