/* eslint-disable no-param-reassign */
import request from '../utils/request';
import post from '../utils/post';
import config from '../utils/config';
import { getDomain } from '../utils/auth';

export async function fetchDomains(basePath, withRoot = false) {
  if (!basePath) {
    const domain = await getDomain();
    if (!domain) {
      throw new Error('Not set domain yet!');
    }
    basePath = domain.path;
  }
  const rootDomainInfo = withRoot ? await request(`${config.apiContextPath}/api/domain/user/info`, { dmPath: basePath }) : null;
  const childrenDomainInfoList = await request(`${config.apiContextPath}/api/domain/user/children-info`, { dmPath: basePath });
  let infoList;
  if (rootDomainInfo && childrenDomainInfoList) {
    infoList = [
      rootDomainInfo,
      ...childrenDomainInfoList,
    ];
  } else if (rootDomainInfo) {
    infoList = [rootDomainInfo];
  } else if (childrenDomainInfoList) {
    infoList = childrenDomainInfoList;
  } else {
    infoList = [];
  }
  return infoList;
}

export async function switchDomain(path) {
  return post(`${config.apiContextPath}/api/domain/user/path`, { dmPath: path });
}

export async function currentDomain() {
  return request(`${config.apiContextPath}/api/domain/user/info`);
}
