import {
  dashboardTranslationKey,
  dashboardOwner,
} from '../../../../frontend/features/cdc-gpsf/dashboard/dashboard-translations';
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { plenarySeedPage, selectPlenarySeeds } from './plenary-labels.seed';
import {
  PSWG_TRANSLATIONS,
  MINISTRY_TRANSLATIONS,
  CDC_TRANSLATIONS,
  CEFP_TRANSLATIONS,
  CDCGPSF_TRANSLATIONS,
  seedTranslationItems,
  type TranslationSeedModule,
  type TranslationSeedItem,
} from './index';
import {
  plenaryDefaults,
  plenaryPage,
  resolvePlenaryLabels,
  fetchPlenaryDictionary,
} from '../../../../frontend/features/pswg/plenary/plenary-translations';

const modules: Array<[TranslationSeedModule, TranslationSeedItem[]]> = [
  ['pswg', PSWG_TRANSLATIONS],
  ['ministry', MINISTRY_TRANSLATIONS],
  ['cdc', CDC_TRANSLATIONS],
  ['cefp', CEFP_TRANSLATIONS],
  ['cdcgpsf', CDCGPSF_TRANSLATIONS],
];
test('every live dashboard label has a matching bilingual seed in each owning module', () => {
  for (const [module, items] of modules) {
    assert.equal(plenarySeedPage(module), plenaryPage(module));
    const labels = items.filter((item) => item.page === plenaryPage(module));
    assert.equal(
      new Set(labels.map((item) => item.translationKey)).size,
      labels.length,
    );
    for (const [key, english] of Object.entries(plenaryDefaults('en'))) {
      const seed = labels.find(
        (item) => item.translationKey === dashboardTranslationKey(key),
      );
      assert.ok(seed, module + '/' + key);
      assert.equal(seed.module, module);
      assert.equal(seed.englishText, english);
      assert.equal(
        seed.khmerText,
        plenaryDefaults('kh')[key as keyof ReturnType<typeof plenaryDefaults>],
      );
    }
  }
});
test('shared component owner comes from exact route segment, not its source directory', () => {
  for (const [module] of modules) {
    assert.equal(
      dashboardOwner(
        '/' +
          (module === 'cdcgpsf' ? 'cdc-gpsf' : module) +
          '/dashboard/working-group',
      ),
      module,
    );
  }
  assert.equal(dashboardOwner('/admin/dashboard'), null);
  assert.equal(dashboardOwner('/pswg-other/dashboard'), null);
});
test('all Admin labels override defaults; sidebar title and page title are independent', () => {
  for (const language of ['en', 'kh', 'km']) {
    const defaults = plenaryDefaults(language);
    const dictionary = Object.fromEntries(
      Object.keys(defaults).map((key) => [
        dashboardTranslationKey(key),
        'Admin:' + key,
      ]),
    );
    const resolved = resolvePlenaryLabels(language, dictionary);
    for (const key of Object.keys(defaults))
      assert.equal(resolved[key as keyof typeof defaults], 'Admin:' + key);
    assert.equal(
      resolvePlenaryLabels(language, { title: 'Sidebar only' }).dashboard,
      defaults.dashboard,
    );
    assert.equal(
      resolvePlenaryLabels(language, { page_title: '   ' }).dashboard,
      defaults.dashboard,
    );
  }
});
test('dictionary request uses correct page/module/km and safely unwraps the API response', async () => {
  const original = globalThis.fetch;
  try {
    for (const [module] of modules) {
      globalThis.fetch = async (input, init) => {
        const url = new URL(String(input));
        assert.equal(url.searchParams.get('module'), module);
        assert.equal(url.searchParams.get('page'), plenaryPage(module));
        assert.equal(url.searchParams.get('language'), 'km');
        assert.equal(init?.cache, 'no-store');
        return Response.json({
          data: {
            data: { translations: { page_title: module, blank: ' ', bad: 4 } },
          },
        });
      };
      assert.deepEqual(await fetchPlenaryDictionary(module, 'kh'), {
        page_title: module,
      });
    }
    globalThis.fetch = async () => new Response('', { status: 500 });
    await assert.rejects(fetchPlenaryDictionary('pswg', 'en'));
  } finally {
    globalThis.fetch = original;
  }
});
test('scoped seed creates parents first, is idempotent and preserves Admin edits', async () => {
  const rows = new Map<string, { id: number; englishText: string }>();
  const id = (value: {
    module: string;
    page: string;
    translationKey: string;
  }) => [value.module, value.page, value.translationKey].join('/');
  const db = {
    translation: {
      async findUnique(args: {
        where: {
          module_page_translationKey: {
            module: string;
            page: string;
            translationKey: string;
          };
        };
      }) {
        return rows.get(id(args.where.module_page_translationKey)) ?? null;
      },
      async create(args: {
        data: TranslationSeedItem & { parentId: number | null };
      }) {
        if (args.data.parentId !== null)
          assert.ok(
            [...rows.values()].some((row) => row.id === args.data.parentId),
          );
        const row = { id: rows.size + 1, englishText: args.data.englishText };
        rows.set(id(args.data), row);
        return row;
      },
    },
  };
  for (const [module, items] of modules) {
    const scoped = selectPlenarySeeds(module, items);
    const first = await seedTranslationItems(db, module, scoped);
    assert.equal(first.created, scoped.length);
    const key = module + '/' + plenaryPage(module) + '/page_title';
    rows.get(key)!.englishText = 'Admin edit';
    const second = await seedTranslationItems(db, module, scoped);
    assert.equal(second.created, 0);
    assert.equal(rows.get(key)!.englishText, 'Admin edit');
  }
});
