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

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


export default async function post(url, data, params = {}, options = {}, auth = true) {
  if (!data) {
    data = {};
  }
  if (auth) {
    const token = await getToken();
    if (!token) {
      return Promise.reject(errors.tokenMissing());
    }
    data.token = encrypt(token);
  }
  let queryParams = 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);
  if (!realOptions.headers) {
    realOptions.headers = {
      Accept: 'application/json',
    };
  }
  realOptions.headers['Content-Type'] = 'application/json';
  realOptions.method = 'POST';
  realOptions.body = JSON.stringify(data);
  return fetch(realUrl, realOptions)
    .then(checkStatus)
    .then(parseObject);
}
