
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/groups`, { access_token: accessToken });
      } catch (e) {
        return [e];
      }

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

      if (result.status !== 201) return [result];

      if (userIds.length) {
        let resultUserIds;
        try {
          resultUserIds = await fetcher.put(`${API_ORIGIN}/api/v1/groups/${result.body.id}/members`, { userIds }, { access_token: accessToken });
        } catch (e) {
          return [e];
        }

        if (resultUserIds.status !== 200) return [resultUserIds];
      }

      if (appIds.length) {
        let resultAppIds;
        try {
          resultAppIds = await fetcher.put(`${API_ORIGIN}/api/v1/groups/${result.body.id}/apps`, { appIds }, { access_token: accessToken });
        } catch (e) {
          return [e];
        }

        if (resultAppIds.status !== 200) return [resultAppIds];
      }

      return [null, result.body];
    },
    async update(id, name, userIds, appIds) {
      let result;
      try {
        result = await fetcher.put(`${API_ORIGIN}/api/v1/groups/${id}/name`, { name }, { access_token: accessToken });
      } catch (e) {
        return [e];
      }

      if (result.status !== 200) return [result];

      try {
        result = await fetcher.put(`${API_ORIGIN}/api/v1/groups/${id}/members`, { userIds }, { access_token: accessToken });
      } catch (e) {
        return [e];
      }

      if (result.status !== 200) return [result];

      try {
        result = await fetcher.put(`${API_ORIGIN}/api/v1/groups/${id}/apps`, { appIds }, { 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/groups/${id}`, null, { access_token: accessToken });
      } catch (e) {
        return [e];
      }

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

export default {
  create,
};
