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

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

  return {
    async list() {
      const page = 1;
      const per_page = 1000;

      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/backups`, { page, per_page, access_token: accessToken });
      } catch (e) {
        error = e;
      }

      if (error || result.status !== 200) return [error || result];
      return [null, result.body.backups];
    },
    async update(id, label, preserveSecs) {
      // if preserveSecs === -1 we will keep it
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/backups/${id}`, { label, preserveSecs }, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

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

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

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

export default {
  create,
};
