import Taro from "@tarojs/taro";
import Headers from "./Header";

export const $fetch = (input, init) => {
  const requestInit = (init ??
    (typeof input === "object" ? input : {})) as RequestInit;
  const url = typeof input === "string" ? input : (input as Request).url;
  const method = requestInit.method ?? "GET";
  const headers = requestInit.headers ?? {};
  const body = requestInit.body;

  return new Promise((resolve) => {
    Taro.request({
      url,
      method: method as any,
      header: headers,
      data: body,
      dataType: "text",
      complete: (evt) => {
        const { statusCode, data, errMsg, header } =
          evt as Taro.request.SuccessCallbackResult;
        // @ts-ignore
        const response = {
          ok: statusCode != null && statusCode >= 200 && statusCode < 300,
          status: statusCode,
          statusText: errMsg,
          headers: new Headers(header ?? {}),
          text: () => Promise.resolve(data),
          json: () =>
            new Promise((res, rej) => {
              try {
                res(JSON.parse(data));
              } catch (err) {
                rej(err);
              }
            }),
        } as Response;

        resolve(response);
      },
    });
  });
};
