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

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

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

      if (result.status !== 200) return [result];
      return [null, result.body.applinks];
    },
    async add(applink) {
      const data = applink;

      let result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/applinks`, data, { access_token: accessToken });
      } catch (e) {
        return [e];
      }

      if (result.status !== 201) return [result];
      return [null];
    },
    async update(id, applink) {
      const data = applink;

      let result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/applinks/${id}`, data, { access_token: accessToken });
      } catch (e) {
        return [e];
      }

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

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

export default {
  create,
};
