import { authorizedFetch } from './authHeaders'; import type { SystemConfigValue, SystemFeature, SystemKbInfo, SystemOverview, SystemSetting, } from '../types/systemAdmin'; const BASE = '/api/v1/admin/system'; async function readError(resp: Response, fallback: string): Promise { let err: Error; try { const text = await resp.text(); err = text ? new Error(text.slice(0, 200)) : new Error(`${fallback} (HTTP ${resp.status})`); } catch { err = new Error(`${fallback} (HTTP ${resp.status})`); } (err as Error & { status?: number }).status = resp.status; return err; } async function getJson(path: string, fallback: string): Promise { const resp = await authorizedFetch(path); if (!resp.ok) throw await readError(resp, fallback); return resp.json() as Promise; } export async function fetchSystemOverview(): Promise { return getJson(`${BASE}/overview`, '获取系统总览失败'); } export async function fetchSystemKb(): Promise { return getJson(`${BASE}/kb`, '获取知识库连接信息失败'); } export async function fetchSystemFeatures(): Promise { const data = await getJson<{ features?: SystemFeature[] }>(`${BASE}/features`, '获取特性开关失败'); return data.features ?? []; } export async function fetchSystemSettings(): Promise { const data = await getJson<{ settings?: SystemSetting[] }>(`${BASE}/settings`, '获取系统设置失败'); return data.settings ?? []; } export async function updateSystemSetting( key: string, value: SystemConfigValue, ): Promise { const resp = await authorizedFetch(`${BASE}/settings/${encodeURIComponent(key)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value }), }); if (!resp.ok) throw await readError(resp, '保存设置失败'); const data = (await resp.json()) as { setting?: SystemSetting } & SystemSetting; return data.setting ?? data; }