import {v4 as uuidv4} from 'uuid';

export const callMethod = async (method, params, notification = false) => {
  const payload = {
    jsonrpc: '2.0',
    method: method,
  };

  if (params) {
    payload.params = params;
  }

  if (!notification) {
    payload.id = uuidv4();
  }

  const response = await window.fetch('/backend/rpc', {
    method: 'POST',
    body: JSON.stringify(payload),
    headers: {
      'Content-Type': 'application/json',
    },
  });

  const result = {};
  try {
    if (!response.ok) {
      throw new Error(`HTTP ${response.status} ${response.statusText}`);
    }

    const data = await response.json();
    if (data.error) {
      throw new Error(`RPC Error: ${data.error.message} ${data.error.data}`);
    }

    result.data = data.result;
  } catch (error) {
    result.error = error;
  }

  return result;
};
