import type { AppConfig, AuthPayload, AuthResponse, DashboardResponse, DownloadItem, HubPageResponse, ServiceOptionsResponse, SessionResponse } from '../shared/contracts' async function request(input: string, init?: RequestInit): Promise { let response: Response try { response = await fetch(input, { ...init, credentials: 'include', headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}), }, }) } catch { throw new Error('Could not reach the OmniArr backend. Check that the server is running.') } if (!response.ok) { const payload = (await safeJson(response)) as { error?: string } | null throw new Error(payload?.error || `${response.status} ${response.statusText}`) } if (response.status === 204) { return undefined as T } return (await response.json()) as T } async function safeJson(response: Response) { try { return await response.json() } catch { return null } } export const api = { getSession: () => request('/api/auth/session'), register: (payload: AuthPayload) => request('/api/auth/register', { method: 'POST', body: JSON.stringify(payload), }), login: (payload: AuthPayload) => request('/api/auth/login', { method: 'POST', body: JSON.stringify(payload), }), logout: () => request('/api/auth/logout', { method: 'POST', }), getSettings: () => request('/api/settings'), saveSettings: (payload: AppConfig) => request<{ config: AppConfig }>('/api/settings', { method: 'PUT', body: JSON.stringify(payload), }), getOptions: () => request('/api/settings/options'), loadJellyfinUsers: (payload: { baseUrl: string; apiKey: string }) => request<{ jellyfinUsers: ServiceOptionsResponse['jellyfinUsers'] }>('/api/settings/jellyfin-users', { method: 'POST', body: JSON.stringify(payload), }), getDashboard: () => request('/api/dashboard'), getHub: (page: HubPageResponse['page']) => request(`/api/hubs/${page}`), getDownloads: () => request('/api/downloads'), requestMovie: (tmdbId: number) => request<{ ok: boolean }>('/api/requests/movie', { method: 'POST', body: JSON.stringify({ tmdbId }), }), requestSeries: (tmdbId: number) => request<{ ok: boolean }>('/api/requests/series', { method: 'POST', body: JSON.stringify({ tmdbId }), }), }