import { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { StorageKeys } from '@/shared/constants/local-storage';
import { setLocalStorage } from '@/shared/lib';

export const finalizeConfig = (config: InternalAxiosRequestConfig) => {
  const { params, data } = config;
  return {
    ...config,
    params,
    data,
  };
};

export const extractAccessToken = (response: AxiosResponse): void => {
  const authHeader = response?.headers?.['authorization'];
  if (authHeader) {
    const accessToken = authHeader.substring(7);
    setLocalStorage(StorageKeys.Jwt, accessToken);
  }
};

export const extractRequestId = (response: AxiosResponse): void => {
  const requestIdHeader = response?.headers?.['x-request-id'];
  if (requestIdHeader) {
    const requestId = requestIdHeader.replaceAll(', *', '');
    setLocalStorage(StorageKeys.RequestId, requestId);
  }
};
