import {fetch} from "@tauri-apps/plugin-http";

// const baseURL = `http://192.168.1.105:3000`
const baseURL = `http://im.congshangyun.com:3000`

const BODY_TYPE = {
  Form: 'Form',
  Json: 'Json',
  Text: 'Text',
  Bytes: 'Bytes',
}

const commonOptions = {
  timeout: 60,
}

const isAbsoluteURL = (url: string): boolean => {
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)
}

const combineURLs = (baseURL: string, relativeURL: string): string => {
  return relativeURL
    ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
    : baseURL
}

const buildFullPath = (baseURL: string, requestedURL: string) => {
  if (baseURL && !isAbsoluteURL(requestedURL)) {
    return combineURLs(baseURL, requestedURL)
  }
  return requestedURL
}

const http = (url: string, options: any = {}) => {
  if (!options.headers) options.headers = {}

  // 解析 body 类型并设置 Content-Type
  if (options?.body) {
    if (options.body.type === BODY_TYPE.Form) {
      options.headers['Content-Type'] = 'multipart/form-data'
    } else if (options.body.type === BODY_TYPE.Json) {
      options.headers['Content-Type'] = 'application/json'
      options.body = JSON.stringify(options.body.body)
    } else if (options.body.type === BODY_TYPE.Text) {
      options.headers['Content-Type'] = 'text/plain'
      options.body = options.body.body.toString()
    } else {
      // 默认处理为 JSON
      options.headers['Content-Type'] = 'application/json'
      options.body = JSON.stringify(options.body)
    }
  }

  options = { ...commonOptions, ...options }
  return fetch(buildFullPath(baseURL, url), options)
    .then(async (response: any) => {
      let responseBody = '';

      if (response.body && typeof response.body.getReader === 'function') {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          responseBody += decoder.decode(value, { stream: true });
        }
        
        // 完成解码后处理最终字符串
        responseBody += decoder.decode(); // flush remaining input
      } else {
        responseBody = response.data || 'No data';
      }
      try {
        return JSON.parse(responseBody);
      } catch (e) {
        console.warn('Response is not JSON, returning raw text:', e);
        return { data: responseBody };
      }
    })
    .catch((err) => {
      console.error(err)
      return Promise.reject(err)
    })
}

export const tauriGet = (url: string, options: any = {}) => {
  options.method = 'GET'
  return http(url, options)
}
export const tauriPost = (url: string, body: any, options: any = {}) => {
  options.method = 'POST'
  options.body = {
    type: BODY_TYPE.Json,
    body: body
  }
  return http(url, options)
}