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

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

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

      if (result.status !== 200) return [result];
      return [null, result.body.apps];
    },
    async get(id, version = '') {
      let url = `${API_ORIGIN}/api/v1/appstore/apps/${id}`;
      if (version && version !== 'latest') url += `/versions/${version}`;

      let result;
      try {
        result = await fetcher.get(url, { access_token: accessToken });
      } catch (e) {
        return [e];
      }

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

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

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

export default {
  create,
};
