import type {INuxtApp, TNuxtApp} from "@/types/app-d-t";
import type {ITranslation} from "@/types/translation-d-t";
import type {IAxios} from "@/types/axios-d-t";
import type {AxiosResponse} from "axios";

export default defineNuxtPlugin(async (nuxtApp: TNuxtApp) => {
    const getDefaultLocale = (): string => {
        const $settings = (nuxtApp as INuxtApp)?.$settings// as ISiteSettings
        const $axios = (nuxtApp as INuxtApp)?.$axios// as IAxios
        const $i18n = (nuxtApp as INuxtApp)?.$i18n

        return String($i18n?.getLocaleCookie() || $i18n?.locale?.value || $settings?.locale || $i18n?.defaultLocale || $axios?.headerLanguage?.value);
    };

    const localTranslations = ref<ITranslation>({
        [getDefaultLocale()]: (await import(`@/locales/${getDefaultLocale()}.json`)).default
    });
    try {
        const {
            data: translationData,
            error: translationError
        } = await useLazyAsyncData(
            'site-translations-' + getDefaultLocale(),
            (): Promise<ITranslation> =>
            (nuxtApp?.$axios as IAxios)?.get('translations', {
                    // baseURL: "http://localhost:3000/api",
                    headers: {
                        'Accept-Language': getDefaultLocale(),
                        'language': getDefaultLocale(),
                    }
                })
                .then((res: AxiosResponse<{ data: ITranslation }>) => {
                    return {
                        [getDefaultLocale()]: ({
                            ...localTranslations.value[getDefaultLocale()],
                            ...(res?.data?.data || {} as ITranslation)
                        })
                    } as ITranslation;
                })
        );

        if (translationError.value) {
            throw translationError.value;
        }
        localTranslations.value = {
            ...localTranslations.value,
            // @ts-ignore
            ...translationData.value
        };
        // nuxtApp.provide('translations', localTranslations);
    } catch (error) {
    }

    nuxtApp.provide('translations', localTranslations);
});