// API服务
// 根据环境变量判断使用哪个 API 地址
const API_BASE = import.meta.env.PROD
  ? 'https://ping.api.shumengya.top/api'  // 生产环境
  : 'http://localhost:8080/api';          // 开发环境

const ADMIN_TOKEN_KEY = 'mengyaping_admin_token';

export function getStoredAdminToken() {
  return localStorage.getItem(ADMIN_TOKEN_KEY);
}

export function setStoredAdminToken(token) {
  if (token) {
    localStorage.setItem(ADMIN_TOKEN_KEY, token);
  } else {
    localStorage.removeItem(ADMIN_TOKEN_KEY);
  }
}

async function parseJsonResponse(response) {
  const data = await response.json();
  return data;
}

// 通用请求（公开读接口）
async function request(url, options = {}) {
  const response = await fetch(`${API_BASE}${url}`, {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  });

  const data = await parseJsonResponse(response);

  if (data.code !== 0) {
    throw new Error(data.message || '请求失败');
  }

  return data.data;
}

async function adminRequest(url, options = {}) {
  const token = getStoredAdminToken();
  if (!token) {
    throw new Error('请先登录管理后台');
  }
  return request(url, {
    ...options,
    headers: {
      ...options.headers,
      'X-Admin-Token': token,
    },
  });
}

/** 校验管理员令牌（登录前调用，不落库） */
export async function verifyAdminToken(token) {
  const response = await fetch(`${API_BASE}/admin/config`, {
    headers: {
      'Content-Type': 'application/json',
      'X-Admin-Token': token,
    },
  });
  const data = await parseJsonResponse(response);
  if (data.code !== 0) {
    throw new Error(data.message || '令牌无效');
  }
  return data.data;
}

// 公开：全局检测周期
export async function getMonitorSettings() {
  return request('/monitor/settings');
}

// 管理端：完整监控配置
export async function getAdminConfig() {
  return adminRequest('/admin/config');
}

export async function updateAdminMonitorConfig(payload) {
  return adminRequest('/admin/config', {
    method: 'PUT',
    body: JSON.stringify(payload),
  });
}

// 获取所有网站状态
export async function getWebsites() {
  return request('/websites');
}

// 获取单个网站状态
export async function getWebsite(id) {
  return request(`/websites/${id}`);
}

// 创建网站
export async function createWebsite(data) {
  return adminRequest('/websites', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

// 更新网站
export async function updateWebsite(id, data) {
  return adminRequest(`/websites/${id}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  });
}

// 删除网站
export async function deleteWebsite(id) {
  return adminRequest(`/websites/${id}`, {
    method: 'DELETE',
  });
}

// 立即检测网站
export async function checkWebsiteNow(id) {
  return adminRequest(`/websites/${id}/check`, {
    method: 'POST',
  });
}

// 获取所有分组
export async function getGroups() {
  return request('/groups');
}

// 获取单个分组
export async function getGroup(id) {
  return request(`/groups/${id}`);
}

// 添加分组
export async function addGroup(name) {
  return adminRequest('/groups', {
    method: 'POST',
    body: JSON.stringify({ name }),
  });
}

// 更新分组
export async function updateGroup(id, payload) {
  return adminRequest(`/groups/${id}`, {
    method: 'PUT',
    body: JSON.stringify(payload),
  });
}

// 删除分组
export async function deleteGroup(id) {
  return adminRequest(`/groups/${id}`, {
    method: 'DELETE',
  });
}
