
import { fetcher } from '@cloudron/pankow';
import { API_ORIGIN } from '../constants.js';

function create() {
  const accessToken = localStorage.token;

  return {
    async config() {
      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/dashboard/config`, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 200) return [error || result];
      return [null, result.body];
    },
    async prepareDomain(domain) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/dashboard/prepare_location`, { domain }, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 202) return [error || result];
      return [null, result.body.taskId];
    },
    async setDomain(domain) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/dashboard/location`, { domain }, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 204) return [error || result];
      return [null];
    },
  };
}

export default {
  create,
};
