import errors from '@/shared/notifications/list';

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null;
}

function getByPath(object: unknown, path: string): unknown {
  return String(path)
    .split('.')
    .reduce<unknown>(
      (acc, key) => (isRecord(acc) ? acc[key] : undefined),
      object,
    );
}

function format(message: string, args: unknown[]): string {
  return message.replace(/{(\d+)}/g, (match, number: string) => {
    const idx = Number(number);
    return typeof args[idx] !== 'undefined' ? String(args[idx]) : match;
  });
}

export function isNotification(key: string): boolean {
  return Boolean(getByPath(errors, key));
}

export function getNotification(key: string, ...args: unknown[]): string {
  const message = getByPath(errors, key);

  if (typeof message !== 'string') {
    return key;
  }

  return format(message, args);
}
