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

function create() {
  return {
    name: 'ProvisionModel',
    async status() {
      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/provision/status`, {});
      } catch (e) {
        error = e;
      }

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

      if (error || result.status !== 200) return [error || result];
      return [null, result.body.devices];
    },
    async createAdmin(data) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/provision/activate`, data);
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 201) return [error || result];
      return [null, result.body.token];
    },
    async detectIp() {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/provision/detect_ip`, {});
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 200) return [error || result];
      return [null, result.body];
    },
    async setup(data) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/provision/setup`, data);
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 200) return [error || result];
      return [null];
    },
    async restore(data) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/provision/restore`, data);
      } catch (e) {
        error = e;
      }

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

export default {
  create,
};
