import type { TrumpPost, Candle, BotTrade, BotPerformance } from '@/types' import type { SignedEnvelope } from './signedRequest' const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000' async function fetchJson(path: string, init?: RequestInit): Promise { const res = await fetch(`${BASE_URL}/api${path}`, { headers: { 'Content-Type': 'application/json' }, ...init, }) if (!res.ok) { let detail = `API error ${res.status}` try { const j = await res.json() if (j.detail) detail = `${res.status}: ${j.detail}` } catch {} throw new Error(detail) } return res.json() as Promise } export async function getPosts(limit = 20, page = 1): Promise { return fetchJson(`/posts?limit=${limit}&page=${page}`) } export async function getPost(id: number): Promise { return fetchJson(`/posts/${id}`) } export async function getPrices(asset: 'BTC' | 'ETH', tf: string): Promise { return fetchJson(`/prices/${asset}?tf=${tf}`) } export async function getTrades(limit = 20, page = 1): Promise { return fetchJson(`/trades?limit=${limit}&page=${page}`) } export async function getPerformance(): Promise { return fetchJson(`/performance`) } export async function subscribe(env: SignedEnvelope): Promise<{ status: string; wallet: string }> { return fetchJson<{ status: string; wallet: string }>(`/subscribe`, { method: 'POST', body: JSON.stringify(env), }) } export interface UserSettings { leverage: number position_size_usd: number take_profit_pct: number | null stop_loss_pct: number | null min_confidence: number daily_budget_usd: number | null active_from: string | null // ISO UTC active_until: string | null // ISO UTC } export interface UserData { wallet_address: string active: boolean subscribed_at: string | null hl_api_key_set: boolean hl_api_key_masked: string | null trades: BotTrade[] settings: UserSettings } export async function setUserSettings( env: SignedEnvelope, settings: UserSettings, ): Promise { return fetchJson(`/user/${env.wallet}/settings`, { method: 'PUT', body: JSON.stringify({ ...env, settings }), }) } export interface UserPublic { wallet_address: string active: boolean hl_api_key_set: boolean } /** No-auth boolean state. Safe to call on every page load. */ export async function getUserPublic(wallet: string): Promise { return fetchJson(`/user/${wallet.toLowerCase()}/public`) } /** Full user data (trades, settings). Requires signed envelope. */ export async function getUser( wallet: string, env: SignedEnvelope, ): Promise { const qs = `ts=${env.timestamp}&sig=${encodeURIComponent(env.signature)}` return fetchJson(`/user/${wallet.toLowerCase()}?${qs}`) } export async function setHlApiKey( env: SignedEnvelope, api_key: string, ): Promise<{ status: string; masked_key: string }> { return fetchJson<{ status: string; masked_key: string }>( `/user/${env.wallet}/hl-api-key`, { method: 'PUT', body: JSON.stringify({ ...env, api_key }), }, ) }