import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
  upsertLanguage,
  getDefaultLocale as getDefaultLocaleImpl,
  isLocaleActive as isLocaleActiveImpl,
} from '@platform-modules/i18n-content';
import {
  bootstrapLocales,
  getDefaultLocale,
  isLocaleActive,
  MOD_CMS_DEFAULT_LOCALES,
} from './i18n-registry.js';

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

const mockedUpsertLanguage = vi.mocked(upsertLanguage);
const mockedGetDefaultLocale = vi.mocked(getDefaultLocaleImpl);
const mockedIsLocaleActive = vi.mocked(isLocaleActiveImpl);

describe('bootstrapLocales', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockedUpsertLanguage.mockResolvedValue(undefined);
  });

  it('calls upsertLanguage once per configured locale with correct args', async () => {
    const db = { transaction: vi.fn() } as never;
    await bootstrapLocales(db);

    expect(mockedUpsertLanguage).toHaveBeenCalledTimes(MOD_CMS_DEFAULT_LOCALES.length);
    for (const locale of MOD_CMS_DEFAULT_LOCALES) {
      expect(mockedUpsertLanguage).toHaveBeenCalledWith(db, locale);
    }
  });

  it('seeds English as default and active', async () => {
    const db = {} as never;
    await bootstrapLocales(db);

    expect(mockedUpsertLanguage).toHaveBeenCalledWith(
      db,
      expect.objectContaining({
        code: 'en',
        nameNative: 'English',
        nameEnglish: 'English',
        direction: 'ltr',
        searchConfig: 'english',
        isActive: true,
        isDefault: true,
      }),
    );
  });
});

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

  it('delegates to the module and returns the default locale code', async () => {
    const db = {} as never;
    mockedGetDefaultLocale.mockResolvedValue('en');

    const code = await getDefaultLocale(db);

    expect(mockedGetDefaultLocale).toHaveBeenCalledWith(db);
    expect(code).toBe('en');
  });
});

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

  it('returns true for an active locale', async () => {
    const db = {} as never;
    mockedIsLocaleActive.mockResolvedValue(true);

    const active = await isLocaleActive(db, 'en');

    expect(mockedIsLocaleActive).toHaveBeenCalledWith(db, 'en');
    expect(active).toBe(true);
  });

  it('returns false for an unknown locale code', async () => {
    const db = {} as never;
    mockedIsLocaleActive.mockResolvedValue(false);

    const active = await isLocaleActive(db, 'xx');

    expect(mockedIsLocaleActive).toHaveBeenCalledWith(db, 'xx');
    expect(active).toBe(false);
  });
});