import type { WalletTransaction } from "@/lib/types" import { httpJson } from "./http" type Paginated = { items: T[] meta: { total: number offset: number limit: number } } export type ListWalletTransactionsOptions = { offset?: number limit?: number } function withOffsetLimit(path: string, options?: ListWalletTransactionsOptions): string { const offset = options?.offset ?? 0 const limit = options?.limit ?? 100 const searchParams = new URLSearchParams({ offset: String(offset), limit: String(limit), }) return `${path}?${searchParams.toString()}` } type WalletBalanceResponse = { balance: string frozenBalance?: string } function parseBalance(value: unknown): number | undefined { if (typeof value !== "object" || value === null) return undefined const v = value as WalletBalanceResponse if (typeof v.balance === "string") return Number(v.balance) if (typeof v.balance === "number") return v.balance return undefined } export async function getWalletBalance(): Promise { const res = await httpJson("/api/v1/wallet/balance", { cache: "no-store" }) const balance = parseBalance(res) if (balance === undefined) { throw new Error("Invalid wallet balance response") } return balance } export async function listWalletTransactions( options?: ListWalletTransactionsOptions, ): Promise { const res = await httpJson>( withOffsetLimit("/api/v1/wallet/transactions", options), { cache: "no-store", }, ) return res.items } export async function topUpWallet(input: { amount: number; method?: string }): Promise { await httpJson("/api/v1/wallet/topup", { method: "POST", json: { amount: String(input.amount), method: input.method ?? "dev", }, }) } export async function withdrawWallet(input: { amount: number; method?: string }): Promise { await httpJson("/api/v1/wallet/withdraw", { method: "POST", json: { amount: String(input.amount), method: input.method ?? "dev", }, }) }