// api.TYPE.resource(json)
// api.GET.users()
// api.PUT['users/1']({name:"bob"})

function newProxy(obj) {
  return new Proxy(obj, {
    get: function(obj, uri) {
      return async (params, json) => {
        const queryString = genQueryString(params);

        const raw = await fetch(
          `/api/v1/${obj.dir || ""}${uri}?${queryString}`,
          {
            method: obj.type,
            body: JSON.stringify(json),
            headers: {
              "Content-Type": "application/json",
              "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
            }
          }
        );
        return await raw.json();
      };
    }
  });
}

function genQueryString(params) {
  return Object.keys(params || {})
    .map(key => key + "=" + params[key])
    .join("&");
}

const api = {
  get: newProxy({ type: "GET" }),
  post: newProxy({ type: "POST" }),
  put: newProxy({ type: "PUT" }),
  patch: newProxy({ type: "PATCH" }),
  delete: newProxy({ type: "DELETE" })
};

export default api;
