import { EIso639OneEnglish } from "../types/iso-639-1/language-key-english.js";
import { EIso639OneGerman } from "../types/iso-639-1/language-key-german.js";
import { EIso639One } from "../types/iso-639-1/language-key.js";

type TLanguage = "de" | `de_${"formal" | "informal"}` | "en";

/**
 * Convert language request headers into ISO 639-1 language code.
 *
 * @example
 * toISOCode('en') // returns 'en'
 * toISOCode('de_formal') // returns 'de'
 * toISOCode('invalid') // returns 'en'
 * @param language Language of request headers
 * @return ISO 639-1 language code or "en" if not found (default)
 */
function findIso6391Code(language: string): EIso639One {
    let targetLanguage = language.toLowerCase();
    if (/[-_]/.test(targetLanguage)) {
        targetLanguage = targetLanguage.split(/[-_]/)[0] ?? targetLanguage;
    }

    return Object.values(EIso639One).find((value) => value === targetLanguage) || EIso639One.English;
}

/**
 * Get key-value pares as object of languages available in ISO 639-1.
 *
 * @param language Language of values
 * @return key-value object with all languages
 */
function iso639OneKeyValue(language: TLanguage = "en") {
    const defaultTranslations = Object.entries(EIso639OneEnglish);
    const languageCodes = Object.values(EIso639One);
    let translations: [string, string][];
    const result: Record<string, string> = {};

    switch (language) {
        case "de":
        case "de_formal":
        case "de_informal":
            translations = Object.entries(EIso639OneGerman);
            break;
        default:
            translations = defaultTranslations;
            break;
    }

    // Fill language codes in result object with translations, and if there is no translation, take it from the default language (en)
    for (const key of languageCodes) {
        const findByKey = ([translationKey]: [string, string]) => translationKey === key;
        result[key] = translations.find(findByKey)?.[1] || defaultTranslations.find(findByKey)?.[1];
    }

    return result;
}

export { findIso6391Code, iso639OneKeyValue };
