// api.ts


// get method
export async function getFetcher(
  input: string | { url: string; arg?: Record<string, unknown> },
  body?: { arg: Record<string, unknown> }
) {
  // 处理不同的输入类型
  let url: string;
  let arg: Record<string, unknown> | undefined;
  
  if (typeof input === 'string') {
    url = input;
    arg = body?.arg;
  } else {
    url = input.url;
    arg = input.arg;
  }
  
  let targetUrl = url;
  
  if (arg) {
    const params = new URLSearchParams();
    for (const [key, value] of Object.entries(arg)) {
      if (value !== undefined && value !== null) {
        if (Array.isArray(value)) {
          value.forEach(v => params.append(key, String(v)));
        } else {
          params.append(key, String(value));
        }
      }
    }
    const queryString = params.toString();
    if (queryString) {
      targetUrl += (url.includes('?') ? '&' : '?') + queryString;
    }
  }

  const response = await fetch(targetUrl, { 
    method: "GET",
    mode: "cors"
  });

  const resp = await response.json();
  
  if (resp.code !== 0) {
    throw new Error(`${resp.message} (${resp.code})`);
  }
  
  return resp.data;
}

// post method
export async function postFetcher(
  url: string,
  body: { arg: Record<string, unknown> | Array<unknown> }
) {
  const resp = (await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body.arg),
    mode: "cors",
  }).then((res) => res.json()));

  if (resp.code !== 0) {
    throw new Error(resp.message + " " + resp.code);
  }
  return resp.data;
}
