import type { Querier } from '@platform-modules/db';
import { getTranslationsFor } from '@platform-modules/i18n-content';
import type { I18nContentSchema } from '@platform-modules/i18n-content';

export async function resolveContentTranslations(
  db: Querier<I18nContentSchema>,
  opts: {
    entityType: 'content' | 'page';
    entityIds: readonly string[];
    locale: string;
    fields?: readonly string[];
    fallbackToDefault?: boolean;
  },
): Promise<Map<string, Record<string, string>>> {
  return getTranslationsFor(db, {
    entityType: opts.entityType,
    entityIds: opts.entityIds,
    locale: opts.locale,
    fields: opts.fields,
    fallbackToDefault: opts.fallbackToDefault,
  });
}

export function coalesceFields<T extends Record<string, string | null>>(
  base: T,
  translations: Record<string, string>,
  fields: readonly (keyof T & string)[],
): T {
  const result = { ...base };
  for (const field of fields) {
    const translated = translations[field];
    if (translated !== undefined && translated !== '') {
      (result as Record<string, string | null>)[field] = translated;
    }
  }
  return result;
}