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

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

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

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

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

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

export default {
  create,
};
