import { ApiLog } from 'src/api-logs/entities/api-log.entity';

export const isEmpty = (data: any) => {
  if (data === undefined || data === null || data === 'null') {
    return true;
  }

  if (typeof data === 'object') {
    if (Object.keys(data).length === 0) {
      return true;
    }
  }

  if (typeof data === 'string') {
    return [''].includes(data.trim());
  }
};

export const getLocalItem = (item: string) => {
  if (typeof window !== 'undefined') {
    return localStorage.getItem(item) || '';
  }
  return '';
};

//to check if image URL already contains domain
export const getCompleteUrl = (partialUrl: string): string | null => {
  if (isEmpty(partialUrl)) {
    return null;
  }

  if (partialUrl.startsWith('https://')) {
    return partialUrl;
  } else {
    return `${process.env.DOMAIN}${partialUrl}`;
  }
};

export const generateErrorLog = (error: Error): ApiLog => {
  const errorLog: ApiLog = {
    id: '',
    header: '',
    form_data: '',
    url: '',
    response_time: '',
    created_at: '',
    response_code: '500',
    error_message: error.message,
    stack_trace: error.stack || '',
    response_body: '',
  };
  return errorLog;
};

export const generateRandomString = (length: number): string => {
  let result = '';
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=-[]{}|;:,.<>?';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }

  return result;
};
