<%
const { apiConfig, generateResponses, config } = it;
%>

import type { AxiosInstance, AxiosRequestConfig, HeadersDefaults, ResponseType, AxiosResponse } from "axios";
import { NiceAxios, NiceAxiosConfig } from 'nice-axios'

export type QueryParamsType = Record<string | number, any>;

export interface FullRequestParams extends Omit<AxiosRequestConfig, "data" | "params" | "url" | "responseType"> {
  /** set parameter to `true` for call `securityWorker` for this request */
  secure?: boolean;
  /** request path */
  path: string;
  /** content type of request body */
  type?: ContentType;
  /** query params */
  query?: QueryParamsType;
  /** format of response (i.e. response.json() -> format: "json") */
  format?: ResponseType;
  /** request body */
  body?: unknown;
}

export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path"> & NiceAxiosConfig;

export interface ApiConfig<SecurityDataType = unknown> extends Omit<AxiosRequestConfig, "data" | "cancelToken"> {
  instance: NiceAxios;
  format?: ResponseType;
}

export enum ContentType {
  Json = "application/json",
  FormData = "multipart/form-data",
  UrlEncoded = "application/x-www-form-urlencoded",
  Text = "text/plain",
}

export class NiceAxiosClient<SecurityDataType = unknown> {
    instance: NiceAxios
    private format?: ResponseType

    constructor({ instance, format, ...axiosConfig }: ApiConfig<SecurityDataType>) {
      this.instance = instance
      this.format = format
    }

    protected stringifyFormItem(formItem: unknown) {
      if (typeof formItem === "object" && formItem !== null) {
        return JSON.stringify(formItem);
      } else {
        return `${formItem}`;
      }
    }

    protected createFormData(input: Record<string, unknown>): FormData {
      return Object.keys(input || {}).reduce((formData, key) => {
        const property = input[key];
        const propertyContent: any[] = (property instanceof Array) ? property : [property]

        for (const formItem of propertyContent) {
          const isFileType = formItem instanceof Blob || formItem instanceof File;
          formData.append(
            key,
            isFileType ? formItem : this.stringifyFormItem(formItem)
            );
        }

        return formData;
      }, new FormData());
    }

    public request = async <T = any, _E = any>({
        secure,
        path,
        type,
        query,
        format,
        body,
        headers,
        ...params
<% if (config.unwrapResponseData) { %>
    }: FullRequestParams): Promise<T> => {
<% } else { %>
    }: FullRequestParams): Promise<AxiosResponse<T>> => {
<% } %>
        const responseFormat = (format || this.format) || undefined;

        if (type === ContentType.FormData && body && body !== null && typeof body === "object") {
          body = this.createFormData(body as Record<string, unknown>);
        }

        if (type === ContentType.Text && body && body !== null && typeof body !== "string") {
          body = JSON.stringify(body);
        }

        return this.instance.request({
            ...params,
            headers: {
                ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
                ...headers,
            },
            params: query,
            responseType: responseFormat,
            data: body,
            url: path,
        })
    };
}
