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

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

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

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

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

      if (error || result.status !== 202) return [error || result];
      return [null];
    },
    async update(id, memoryLimit, recoveryMode) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/services/${id}`, {memoryLimit, recoveryMode}, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 202) return [error || result];
      return [null];
    },
    async getPlatformStatus() {
      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/services/platform_status`, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

export default {
  create,
};
