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

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

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

      if (error || result.status !== 200) return [error || result];
      return [null, result.body.registries];
    },
    async add(provider, serverAddress, username, email, password) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/docker/registries`, { provider, serverAddress, username, email, password }, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

      if (error || result.status !== 200) return [error || result];
      return [null, result.body];
    },
    async update(id, provider, serverAddress, username, email, password) {
      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/docker/registries/${id}`, { provider, serverAddress, username, email, password }, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

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

export default {
  create,
};
