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

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

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

      if (error || result.status !== 200) return [error || result];
      return [null, result.body.update];
    },
    async getAutoupdateConfig() {
      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/updater/autoupdate_config`, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

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

      if (error || result.status !== 200) return [error || result];
      return [null];
    },
    async update(skipBackup = false) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/updater/box_update`, { skipBackup }, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

export default {
  create,
};
