import {ref} from 'vue';
import {convertSiteSettingsResponse} from "@/plugins/data/site-settings-data";
import type {ISiteSettings} from "@/types/site-settings-d-t";
import type {ILocale} from "@/types/locale-d-t";
import type {INuxtApp, TNuxtApp} from "@/types/app-d-t";

export default defineNuxtPlugin(async (nuxtApp: TNuxtApp) => {
    const settings = ref<ISiteSettings | null>(null);
    const config = useRuntimeConfig();

    const getDefaultLocale = () => {
        const $settings = (nuxtApp as INuxtApp)?.$settings// as ISiteSettings
        const $axios = (nuxtApp as INuxtApp)?.$axios// as IAxios
        const $i18n = (nuxtApp as INuxtApp)?.$i18n

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

    try {
        const {data, error} = await useLazyAsyncData('site-settings', () =>
            // @ts-ignore
            nuxtApp?.$axios?.get('site-settings', {
                headers: {
                    'Accept-Language': getDefaultLocale(),
                    'language': getDefaultLocale(),
                }
            }).then((res: any) => convertSiteSettingsResponse(res?.data?.data || {}))
        );

        if (error.value) {
            console.error('Failed to load default settings:', error.value);
            return;
        }

        settings.value = (data.value || convertSiteSettingsResponse({})) as ISiteSettings;
        settings.value.noImageUrl = settings.value?.noImageUrl || config?.public?.noImageUrl
        settings.value.apiUrl = config?.public?.apiUrl
        settings.value.baseUrl = config?.public?.baseUrl
        settings.value.perPage = Number(settings.value?.perPage || config?.public?.perPage || 9)
        settings.value.perRow = Number(settings.value?.perRow || config?.public?.perRow || 3)
        settings.value.siteTitle = settings.value?.siteTitle || config?.public?.siteTitle
        settings.value.updateSlugOnLocale = Boolean(settings.value?.updateSlugOnLocale === undefined ? config?.public?.updateSlugOnLocale : settings.value.updateSlugOnLocale)

        nuxtApp.provide('settings', settings.value);
        nuxtApp.provide('locales', (settings.value?.locales || []) as ILocale[]);
        nuxtApp.provide('locale', (settings.value?.locale || '') as string);
        nuxtApp.provide('baseUrl', settings.value?.baseUrl);

        // return {
        //     provide: {
        //         settings: settings.value,
        //     },
        // };
    } catch (error) {
        console.error('Failed to load default settings:', error);
    }
});
