/** Central dashboard API base (no trailing slash). Dev default uses Vite proxy. */
export const centralApiBase = (): string => {
  const v = import.meta.env.VITE_CENTRAL_API_URL as string | undefined;
  return (v && v.trim()) || '/central-api';
};

export async function fetchPublicServers(): Promise<
  { id: string; name: string; url: string; enabled: boolean }[]
> {
  const base = centralApiBase();
  const res = await fetch(`${base}/api/servers`);
  if (!res.ok) {
    throw new Error(`无法加载服务器列表 (${res.status})`);
  }
  const body = await res.json();
  const data = body.data;
  if (!Array.isArray(data)) {
    throw new Error('无效的服务器列表响应');
  }
  return data;
}

export async function verifyAdminToken(token: string): Promise<boolean> {
  const base = centralApiBase();
  const res = await fetch(`${base}/api/admin/auth`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ token }),
  });
  return res.ok;
}

const adminHeaders = (token: string, json = false): HeadersInit => {
  const h: Record<string, string> = { 'X-Admin-Token': token };
  if (json) h['Content-Type'] = 'application/json';
  return h;
};

export async function adminListServers(token: string) {
  const base = centralApiBase();
  const res = await fetch(`${base}/api/admin/servers`, { headers: adminHeaders(token) });
  if (res.status === 401) throw new Error('UNAUTHORIZED');
  if (!res.ok) throw new Error(`加载失败 (${res.status})`);
  const body = await res.json();
  return body.data as {
    id: string;
    name: string;
    url: string;
    enabled: boolean;
    sortOrder: number;
    agentKey?: string;
  }[];
}

export async function adminCreateServer(
  token: string,
  payload: { name: string; url?: string; enabled: boolean }
) {
  const base = centralApiBase();
  const res = await fetch(`${base}/api/admin/servers`, {
    method: 'POST',
    headers: adminHeaders(token, true),
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error((err as { error?: string }).error || `创建失败 (${res.status})`);
  }
  return (await res.json()).data;
}

export async function adminUpdateServer(
  token: string,
  id: string,
  payload: { name: string; url?: string; enabled: boolean; agentKey?: string }
) {
  const base = centralApiBase();
  const res = await fetch(`${base}/api/admin/servers/${encodeURIComponent(id)}`, {
    method: 'PUT',
    headers: adminHeaders(token, true),
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error((err as { error?: string }).error || `更新失败 (${res.status})`);
  }
  return (await res.json()).data;
}

export async function adminDeleteServer(token: string, id: string) {
  const base = centralApiBase();
  const res = await fetch(`${base}/api/admin/servers/${encodeURIComponent(id)}`, {
    method: 'DELETE',
    headers: adminHeaders(token, false),
  });
  if (!res.ok) throw new Error(`删除失败 (${res.status})`);
}

export async function adminReorderServers(token: string, ids: string[]) {
  const base = centralApiBase();
  const res = await fetch(`${base}/api/admin/servers/reorder`, {
    method: 'PUT',
    headers: adminHeaders(token, true),
    body: JSON.stringify({ ids }),
  });
  if (!res.ok) throw new Error(`排序失败 (${res.status})`);
}

export const ADMIN_TOKEN_STORAGE = 'mengya_monitor_admin_token';
