import { describe, it, expect, vi, beforeEach } from 'vitest';
import { getTranslationsFor } from '@platform-modules/i18n-content';
import { coalesceFields, resolveContentTranslations } from './content-i18n.js';

vi.mock('@platform-modules/i18n-content', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@platform-modules/i18n-content')>();
  return {
    ...actual,
    getTranslationsFor: vi.fn(),
  };
});

const mockedGetTranslationsFor = vi.mocked(getTranslationsFor);

describe('coalesceFields', () => {
  const base = { title: 'Base Title', body: 'Base Body', slug: 'base-slug' };

  it('prefers a non-empty translation over the base value', () => {
    const result = coalesceFields(base, { title: 'Translated Title' }, ['title']);
    expect(result).toEqual({ title: 'Translated Title', body: 'Base Body', slug: 'base-slug' });
    expect(result).not.toBe(base);
  });

  it('keeps the base value when the translation is missing', () => {
    const result = coalesceFields(base, {}, ['title', 'body']);
    expect(result).toEqual(base);
    expect(result).not.toBe(base);
  });

  it('keeps the base value when the translation is an empty string', () => {
    const result = coalesceFields(base, { title: '' }, ['title']);
    expect(result.title).toBe('Base Title');
  });
});

describe('resolveContentTranslations', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('passes entityType, entityIds, locale, and fields to getTranslationsFor', async () => {
    const db = {} as never;
    const translations = new Map([
      ['id-1', { title: 'T1' }],
      ['id-2', { title: 'T2' }],
    ]);
    mockedGetTranslationsFor.mockResolvedValue(translations);

    const result = await resolveContentTranslations(db, {
      entityType: 'content',
      entityIds: ['id-1', 'id-2'],
      locale: 'fr',
      fields: ['title'],
      fallbackToDefault: true,
    });

    expect(mockedGetTranslationsFor).toHaveBeenCalledWith(db, {
      entityType: 'content',
      entityIds: ['id-1', 'id-2'],
      locale: 'fr',
      fields: ['title'],
      fallbackToDefault: true,
    });
    expect(result).toBe(translations);
    expect(result.get('id-1')).toEqual({ title: 'T1' });
    expect(result.get('id-2')).toEqual({ title: 'T2' });
  });

  it('returns a Map keyed by entityId', async () => {
    const db = {} as never;
    mockedGetTranslationsFor.mockResolvedValue(
      new Map([['page-1', { title: 'Page FR', body: 'Corps' }]]),
    );

    const result = await resolveContentTranslations(db, {
      entityType: 'page',
      entityIds: ['page-1'],
      locale: 'fr',
    });

    expect(result).toBeInstanceOf(Map);
    expect(result.get('page-1')).toEqual({ title: 'Page FR', body: 'Corps' });
  });
});