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

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

  const domainsModel = DomainsModel.create();

  return {
    async list() {
      const page = 1;
      const per_page = 1000;

      let error, result;
      try {
        result = await fetcher.get(`${API_ORIGIN}/api/v1/archives`, { page, per_page, access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

      if (error || result.status !== 204) return [error || result];
      return [null];
    },
    async restore(id, data) {
      // preflight domain checks
      if (!data.overwriteDns) {
        const allDomains = [{ domain: data.domain, subdomain: data.subdomain }].concat(Object.keys(data.secondaryDomains).map(function (k) {
          return {
            domain: data.secondaryDomains[k].domain,
            subdomain: data.secondaryDomains[k].subdomain
          };
        }));

        for (const domain of allDomains) {
          const [error, result] = await domainsModel.checkRecords(domain.domain, domain.subdomain);
          if (error) return [error];

          const fqdn = domain.subdomain + '.' + domain.domain;

          if (result.error) {
            if (result.error.reason === 'Access Denied') return [{ type: 'provider', fqdn, message: 'DNS credentials for ' + domain.domain + ' are invalid. Update it in Domains & Certs view' }];
            return [{ type: 'provider', fqdn, message: result.error.message }];
          }

          if (result.needsOverwrite) {
            return [{ type: 'externally_exists', fqdn, message: 'DNS Record already exists. Confirm that the domain is not in use for services external to Cloudron' }];
          }
        }
      }

      let error, result;
      try {
        result = await fetcher.post(`${API_ORIGIN}/api/v1/archives/${id}/unarchive`, data, { access_token: accessToken });
      } catch (e) {
        error = e;
      }

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

export default {
  create,
};
