import _ from 'lodash';
import { fetch } from './polyfill';
import { encrypt } from './helper';
import { errors } from './error';
import { getToken } from './auth';
import { checkStatus, normParams, parseObject } from './http-helper';

const defaultOptions = {
  headers: { Accept: 'application/json' },
};

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param auth
 * @param params
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default async function doDelete(url, params = {}, options = {}, auth = true) {
  let token;
  if (auth) {
    token = await getToken();
    if (!token) {
      return Promise.reject(errors.tokenMissing());
    }
    token = encrypt(token);
  }
  let queryParams = token ? [...normParams(params), ['token', token]] : normParams(params);
  queryParams = queryParams.map(([k, v]) => (_.isNil(v) ? k : `${k}=${encodeURIComponent(v)}`));
  queryParams = queryParams.join('&');
  let realUrl = url;
  if (queryParams) {
    realUrl = `${url}?${queryParams}`;
  }
  const realOptions = _.defaults(options, defaultOptions);
  realOptions.method = 'DELETE';
  return fetch(realUrl, realOptions)
    .then(checkStatus)
    .then(parseObject);
}

