import assert from 'node:assert/strict';
import { test } from 'node:test';
import {
  PSWG_TRANSLATIONS, MINISTRY_TRANSLATIONS, CDC_TRANSLATIONS, CEFP_TRANSLATIONS, CDCGPSF_TRANSLATIONS,
  seedTranslationItems,
} from './index';
import { PROFILE_MENU_KEYS, fetchProfileMenuDictionary, resolveProfileMenuLabels } from '../../../../frontend/components/layout/header/profile-menu-translations';
import { profileMenuSeeds } from './profile-menu-labels.seed';
import { chooseProfileMenuSource } from './profile-menu-merge';
import { translations } from '../../../../frontend/components/layout/header/header-data';

test('one shared menu seeds each bilingual label and modules contain no duplicates', () => {
  for (const items of [PSWG_TRANSLATIONS, MINISTRY_TRANSLATIONS, CDC_TRANSLATIONS, CEFP_TRANSLATIONS, CDCGPSF_TRANSLATIONS]) {
    assert.equal(items.filter(item => item.page === 'profile_menu').length, 0);
  }
  {
    const labels = profileMenuSeeds();
    assert.equal(labels.length, 7);
    assert.ok(labels.every(item => item.module === 'shared'));
    const root = labels.find(item => item.translationKey === 'page_title')!;
    assert.equal(root.parent, undefined);
    for (const [key, apiKey] of Object.entries(PROFILE_MENU_KEYS)) {
      const label = labels.find(item => item.translationKey === apiKey)!;
      assert.ok(label);
      assert.equal(label.englishText, translations.en[key as keyof typeof PROFILE_MENU_KEYS]);
      assert.equal(label.khmerText, translations.kh[key as keyof typeof PROFILE_MENU_KEYS]);
      assert.deepEqual(label.parent, { module: root.module, page: root.page, translationKey: root.translationKey });
    }
  }
});

test('seeding twice preserves Admin edits and parent links', async () => {
  const rows = new Map<string, { id: number; englishText: string; parentId: number | null }>();
  const db = { translation: {
    async findUnique({ where }: { where: { module_page_translationKey: { translationKey: string } } }) {
      return rows.get(where.module_page_translationKey.translationKey) ?? null;
    },
    async create({ data }: { data: { translationKey: string; englishText: string; parentId: number | null } }) {
      const row = { ...data, id: rows.size + 1 };
      rows.set(data.translationKey, row);
      return row;
    },
  } };
  const labels = profileMenuSeeds();
  assert.equal((await seedTranslationItems(db, 'shared', labels)).created, 7);
  rows.get('logout')!.englishText = 'Admin edited sign out';
  assert.equal((await seedTranslationItems(db, 'shared', labels)).kept, 7);
  assert.equal(rows.get('logout')!.englishText, 'Admin edited sign out');
  assert.equal(rows.get('logout')!.parentId, rows.get('page_title')!.id);
});

test('migration prefers edited legacy values, then the latest edit; existing shared edits always win', () => {
  const base = { id: 1, module: 'pswg', translationKey: 'logout', englishText: 'Logout', khmerText: 'ចាកចេញ', isActive: true, updatedAt: new Date('2026-10-25') };
  const edited = { ...base, id: 2, module: 'ministry', englishText: 'Sign out', updatedAt: new Date('2026-10-24') };
  assert.equal(chooseProfileMenuSource([base, edited], 'logout'), edited);
  const newer = { ...edited, id: 3, module: 'cdc', englishText: 'Leave', updatedAt: new Date('2026-10-26') };
  assert.equal(chooseProfileMenuSource([edited, newer], 'logout'), newer);
  const shared = { ...edited, module: 'shared' };
  assert.equal(chooseProfileMenuSource([shared, newer], 'logout'), shared);
});

test('dictionary requests use km, accept nested envelopes, and fall back for missing labels', async (t) => {
  t.mock.method(globalThis, 'fetch', async (input: string) => {
    const url = new URL(input);
    assert.equal(url.searchParams.get('module'), 'shared');
    assert.equal(url.searchParams.get('page'), 'profile_menu');
    assert.equal(url.searchParams.get('language'), 'km');
    return new Response(JSON.stringify({ data: { success: true, data: { translations: { logout: 'Admin label', language: ' ', download_app: 4 } } } }));
  });
  const labels = resolveProfileMenuLabels('kh', await fetchProfileMenuDictionary('kh'));
  assert.equal(labels.logout, 'Admin label');
  assert.equal(labels.language, translations.kh.language);
  assert.equal(labels.downloadApp, translations.kh.downloadApp);
  assert.equal(resolveProfileMenuLabels('en', {}).logout, 'Logout');
});
