import { UnknownLocaleError, getTranslationsFor, listLanguages } from "@platform-modules/i18n-content";
import { getEntityTranslationStatusFor } from "@platform-modules/i18n-translator";
//#region src/i18n.ts
const PRODUCT_TRANSLATABLE_FIELDS = ["title", "description"];
function productFieldList(fields) {
	return fields && fields.length > 0 ? fields : PRODUCT_TRANSLATABLE_FIELDS;
}
function coalesceFieldValue(row, field, translated) {
	if (translated !== void 0) return translated;
	return row[field];
}
async function validateLocales(q, locale, defaultLocale) {
	const languages = await listLanguages(q);
	const active = new Set(languages.filter((language) => language.isActive).map((language) => language.code));
	if (!active.has(locale)) throw new UnknownLocaleError(locale);
	if (defaultLocale !== void 0 && !active.has(defaultLocale)) throw new UnknownLocaleError(defaultLocale);
	const resolvedDefault = defaultLocale ?? languages.find((language) => language.isDefault)?.code;
	if (resolvedDefault !== void 0 && !active.has(resolvedDefault)) throw new UnknownLocaleError(resolvedDefault);
	return resolvedDefault;
}
async function localizeProducts(q, rows, args) {
	if (rows.length === 0) return [];
	const fields = productFieldList(args.fields);
	await validateLocales(q, args.locale, args.defaultLocale);
	if (args.locale === args.defaultLocale || fields.length === 0) return rows.map((row) => ({ ...row }));
	const translations = await getTranslationsFor(q, {
		entityType: "product",
		entityIds: rows.map((row) => row.id),
		locale: args.locale,
		fields
	});
	return rows.map((row) => {
		const localized = { ...row };
		const translatedFields = translations.get(row.id) ?? {};
		for (const field of fields) localized[field] = coalesceFieldValue(row, field, translatedFields[field]);
		return localized;
	});
}
function productVisibleInLocale(status) {
	return status === "complete";
}
async function filterVisibleInLocale(q, rows, args) {
	if (rows.length === 0) return [];
	const fields = productFieldList(args.fields);
	const defaultLocale = await validateLocales(q, args.locale);
	if (args.locale === defaultLocale || fields.length === 0) return [...rows];
	const statuses = await getEntityTranslationStatusFor(q, {
		entityType: "product",
		entityIds: rows.map((row) => row.id),
		locale: args.locale,
		fields
	});
	return rows.filter((row) => productVisibleInLocale(statuses.get(row.id) ?? "missing"));
}
//#endregion
export { filterVisibleInLocale, localizeProducts, productVisibleInLocale };
