import type { InterceptionRule, Command, CreateRuleRequest, UpdateRuleRequest, UpdateCommandRequest, RequestLogs, } 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, }), }), }; // Logs API export const logsApi = { list: (params?: { method?: string; search?: string; page: number; limit: number }) => { const query = new URLSearchParams(); if (params?.method) { query.set("method", params.method); } if (params?.search) { query.set("search", params.search); } const queryString = query.toString(); return request(`/logs${queryString ? `?${queryString}` : ""}`); }, methods: () => { return request("/logs/methods"); }, };