export default defineNuxtPlugin((nuxtApp) => {
    const auth = useAuthStore();
    const config = useRuntimeConfig();

    const api = $fetch.create({
        baseURL: `${config.public.apiBase}`,
        onRequest({ request, options, error }) {
            if (auth.accessToken) {
                options.headers.set('Authorization', `Bearer ${auth.accessToken}`)
            }
        },
        async onResponseError({ response, options }) {
            const originalRequest = { ...options };

            if (response.status === 401) {
                const success = await auth.refresh();

                if (success) {
                    originalRequest.headers = {
                        ...originalRequest.headers,
                        Authorization: `Bearer ${auth.accessToken}`
                    };

                    await $fetch(response.url, originalRequest);
                } else {
                    nuxtApp.runWithContext(() => navigateTo('/auth/login'));
                }
            }

            throw response._data || new Error('Unknown API error');
        }
    })

    return {
        provide: {
            api
        }
    }
})
