import type { ResourceLanguage } from 'i18next';

const isResourceObject = (value: unknown): value is Record<string, unknown> => {
  return typeof value === 'object' && value != null && !Array.isArray(value);
};

const asResourceLanguage = (value: unknown): ResourceLanguage => {
  if (isResourceObject(value)) {
    return value as ResourceLanguage;
  }
  return {};
};

export const __test = {
  isResourceObject,
  asResourceLanguage,
} as const;

/**
 * Deep-merges i18next resource language objects while preserving nested keys.
 */
export function mergeResourceLanguages(
  ...values: readonly ResourceLanguage[]
): ResourceLanguage {
  const output: ResourceLanguage = {};

  values.forEach((value) => {
    Object.entries(value).forEach(([key, nextValue]) => {
      const currentValue = output[key];
      if (isResourceObject(currentValue) && isResourceObject(nextValue)) {
        output[key] = mergeResourceLanguages(
          asResourceLanguage(currentValue),
          asResourceLanguage(nextValue),
        );
        return;
      }
      output[key] = nextValue;
    });
  });

  return output;
}
