import type { Post, Settings, InteractionConfig, Asset, APIKey, AnalyticsSummary } from './types' const BASE = '/api/studio' async function request(path: string, options?: RequestInit): Promise { const res = await fetch(`${BASE}${path}`, { ...options, headers: { 'Content-Type': 'application/json', ...options?.headers, }, }) if (!res.ok) { const error = await res.json().catch(() => ({ error: res.statusText })) throw new Error(error.error || 'Request failed') } if (res.status === 204) return undefined as T return res.json() } export const api = { posts: { list: () => request('/posts'), get: (slug: string) => request(`/posts/${slug}`), create: (data: Partial) => request('/posts', { method: 'POST', body: JSON.stringify(data), }), update: (slug: string, data: Partial) => request(`/posts/${slug}`, { method: 'PUT', body: JSON.stringify(data), }), delete: (slug: string) => request(`/posts/${slug}`, { method: 'DELETE' }), }, settings: { get: () => request('/settings'), update: (data: Settings) => request<{ success: boolean }>('/settings', { method: 'PUT', body: JSON.stringify(data), }), }, interactions: { get: () => request('/interaction-config'), update: (data: Partial) => request('/interaction-config', { method: 'PUT', body: JSON.stringify(data), }), }, assets: { list: () => request('/assets'), upload: async (file: File): Promise => { const form = new FormData() form.append('file', file) const res = await fetch(`${BASE}/assets`, { method: 'POST', body: form }) if (!res.ok) throw new Error('Upload failed') return res.json() }, delete: (id: string) => request(`/assets/${id}`, { method: 'DELETE' }), }, apiKeys: { list: () => request('/api-keys'), create: (name: string) => request('/api-keys', { method: 'POST', body: JSON.stringify({ name }), }), delete: (key: string) => request(`/api-keys/${key}`, { method: 'DELETE' }), }, analytics: { get: (days = 30) => request(`/analytics?days=${days}`), getPost: (slug: string, days = 30) => request(`/analytics/posts/${slug}?days=${days}`), }, }