export const get = async (url: string) => {
  const res = await fetch(url);

  if (!res.ok) {
    throw new Error(`HTTP error ${res.status}`);
  }

  const json = await res.json();

  if (json?.error) {
    throw new Error(json.error);
  }

  return json;
};

export const post = async ([url, data]: [url: string, data: object]) => {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });

  const json = await res.json();

  if (!res.ok) {
    if (res.status === 422) {
      return { alreadyProcessed: true };
    }
    throw new Error(`HTTP error ${res.status}`);
  }

  return json;
};

export const put = async ([url, data]: [url: string, data: object]) => {
  const res = await fetch(url, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });

  const json = await res.json();

  if (!res.ok) {
    if (res.status === 422) {
      return { alreadyProcessed: true };
    }
    throw new Error(`HTTP error ${res.status}`);
  }

  return json;
};
