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

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

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

      if (error || result.status !== 200) return [error || result];
      return [null, result.body.appPasswords];
    },
    async add(identifier, name, expiresAt) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/app_passwords`, { identifier, name, expiresAt }, { 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/app_passwords/${id}`, null, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

export default {
  create,
};
