import i18next from 'i18next';

import { BaseLanguageCode, Language, Languages } from 'src/constants/languages';
import { changeLanguageUser } from 'src/services/users';
import { MeUser } from 'src/types/user';

export const getLanguageOptions = () => {
  return Object.values(Languages)
    .sort()
    .map(language => ({
      value: language,
      label: `LANGUAGES:LANGUAGE_${language}`,
    }));
};

/**
 * Retrieves the user's browser language setting and returns its base language code.
 * @returns {BaseLanguageCode} The two-character base language code from the browser's language setting
 */
export const getNavigatorLanguage = () => {
  return navigator.language.slice(0, 2) as BaseLanguageCode;
};

/**
 * Sets the language of the document element.
 * @param {Language} language - The language to set the document to.
 */
export const setDocumentLanguage = (language: Language) => {
  document.documentElement.lang = language;
};

/**
 * Handles user language settings during login process
 * @param user - The user object
 * @param accessToken - The access token for API calls
 * @returns Promise<string> - The final language to use
 */
export const handleUserLanguage = async (
  user: MeUser,
  accessToken: string,
): Promise<string> => {
  let language = user.language;

  if (!user?.hasBeenLogged) {
    const headers = { headers: { Authorization: `Bearer ${accessToken}` } };
    await changeLanguageUser(user.id, i18next.language, headers);
    i18next.changeLanguage(i18next.language);
    setDocumentLanguage(i18next.language as Language);
    language = i18next.language;
  } else if (user?.language !== i18next.language) {
    i18next.changeLanguage(user.language);
    setDocumentLanguage(user.language as Language);
  }

  return language;
};
