import type { AxiosRequestConfig } from 'axios';

import GeneralApi, { authenticatedRequest } from '@northern.tech/store/api/general-api';

// Mission Portal's PHP layer html-encodes API responses so the legacy AngularJS/JQuery
// views can inject them as HTML. React escapes on render, so ask the proxy for
// the raw payload instead.
export const CF_HTML_ENCODE_HEADER = 'Cf-Html-Encode';

authenticatedRequest.interceptors.request.use(config => {
  config.headers[CF_HTML_ENCODE_HEADER] = 'false';
  return config;
});

const postUnauthorized = <T = unknown, D = unknown>(
  url: string,
  data?: D,
  config: AxiosRequestConfig = {}
) =>
  GeneralApi.postUnauthorized<T, D>(url, data, {
    ...config,
    headers: { [CF_HTML_ENCODE_HEADER]: 'false', ...config.headers }
  });

export const formEncoded = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } };

const Api = { ...GeneralApi, postUnauthorized };

export default Api;
