import type { InterceptionRule, Command, CreateRuleRequest, UpdateRuleRequest, UpdateCommandRequest } from '../types'; import { authStore } from './auth'; const API_BASE = '/admin/api'; async function request( endpoint: string, options?: RequestInit ): Promise { const token = authStore.getToken(); const response = await fetch(`${API_BASE}${endpoint}`, { headers: { 'Content-Type': 'application/json', ...(token ? { 'Authorization': `Bearer ${token}` } : {}), ...options?.headers, }, ...options, }); if (response.status === 401) { // Unauthorized - clear token and trigger re-authentication authStore.clearToken(); window.location.reload(); throw new Error('Unauthorized'); } if (!response.ok) { const error = await response.json().catch(() => ({ error: response.statusText })); throw new Error(error.error || `API Error: ${response.statusText}`); } if (response.status === 204 || response.status === 200) { // Check if response has content const contentType = response.headers.get('content-type'); if (!contentType || !contentType.includes('application/json')) { return undefined as T; } // Check if there's actually content to parse const text = await response.text(); if (!text || text.trim() === '') { return undefined as T; } return JSON.parse(text); } return response.json(); } // Rules API export const rulesApi = { list: () => request('/rules'), create: (rule: CreateRuleRequest) => request('/rules', { method: 'POST', body: JSON.stringify(rule), }), update: (id: number, rule: UpdateRuleRequest) => request(`/rules/${id}`, { method: 'PUT', body: JSON.stringify(rule), }), delete: (id: number) => request(`/rules/${id}`, { method: 'DELETE' }), }; // Commands API export const commandsApi = { list: (status?: string) => request(`/commands${status ? `?status=${status}` : ''}`), updateStatus: (id: number, req: UpdateCommandRequest) => request(`/commands/${id}`, { method: 'POST', body: JSON.stringify(req), }), }; // Config API export const configApi = { get: () => request>('/config'), update: (config: Record) => request('/config', { method: 'PUT', body: JSON.stringify(config), }), }; // Auth API export const authApi = { changePassword: (oldPassword: string, newPassword: string) => request('/password', { method: 'PUT', body: JSON.stringify({ old_password: oldPassword, new_password: newPassword, }), }), };