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

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

  return {
    async list(domain) {
      let result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/mail/${domain}/lists`, { page: 1, per_page: 1000, access_token: accessToken });
      } catch (e) {
        return [e];
      }

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

      if (result.status !== 200) return [result];
      return [null, result.body.list];
    },
    async add(domain, name, options) {
      const data = {
        name: name,
        members: options.members || [],
        membersOnly: !!options.membersOnly,
        active: !!options.active,
      };

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

      if (result.status !== 201) return [result];
      return [null];
    },
    async update(domain, name, options) {
      const data = {
        members: options.members || [],
        membersOnly: !!options.membersOnly,
        active: !!options.active,
      };

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

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

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

export default {
  create,
};
