import { getRequestConfig } from 'next-intl/server'
import { cookies } from 'next/headers'

const COOKIE_NAME = 'language'
const languages = ['ru', 'en']
const defaultLanguage: Language = 'ru'

type Language = (typeof languages)[number]

////////////

export async function getCurrentLanguage() {
	const cookiesStore = await cookies()

	const language = cookiesStore.get(COOKIE_NAME)?.value ?? defaultLanguage

	return language
}

////////////

export async function setCurrentLanguage(language: Language) {
	const cookiesStore = await cookies()

	return cookiesStore.set(COOKIE_NAME, language)
}

////////////

export default getRequestConfig(async () => {
	const language = await getCurrentLanguage()

	return {
		locale: language,
		messages: {
			datasets: (
				await import(`../../public/locales/${language}/datasets.json`)
			).default,
			errors: (
				await import(`../../public/locales/${language}/errors.json`)
			).default,
			...(await import(`../../public/locales/${language}/general.json`))
				.default
		}
	}
})
