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

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

  return {
    async list(acknowledged = null, page = 1) {
      const query = {
        access_token: accessToken,
        page,
        per_page: 100
      };

      if (acknowledged !== null) query.acknowledged = !!acknowledged;

      let result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/notifications`, query);
      } catch (e) {
        return [e];
      }

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

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

export default {
  create,
};
