import type { GridData, AppSettings } from './types' const BASE = '/twin-optimiser/api' async function request(path: string, opts?: RequestInit): Promise { const res = await fetch(BASE + path, { credentials: 'include', ...opts }) if (res.status === 401) { ;(window.top ?? window).location.href = '/login' throw new Error('Unauthenticated') } if (!res.ok) { const body = await res.json().catch(() => ({})) as { error?: string } throw new Error(body.error || `HTTP ${res.status}`) } return res.json() as Promise } export function getGrid(startDate?: string, days = 14, force = false): Promise { const p = new URLSearchParams() if (startDate) p.set('start_date', startDate) p.set('days', String(days)) if (force) p.set('force', '1') return request(`/grid?${p}`) } export function getSettings(): Promise { return request('/settings') } export function postSettings(settings: Partial): Promise { return request('/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(settings), }) } export function testNewbook(): Promise<{ ok: boolean; message?: string; error?: string }> { return request('/newbook/test', { method: 'POST' }) }