import { expect, type Page } from '../fixtures.js';
import { openCreateDialog, saveDialog, fillNumberInput } from './settings.js';

/**
 * Create a university through the settings dialog. Shared between
 * universities.spec (its own CRUD coverage) and courses.spec (which
 * seeds a university so the course dialog's autocomplete has a
 * deterministic match) so the flake lessons — commit the factor via
 * keystrokes+blur, hard-assert the country suggestion — live in ONE
 * place instead of drifting per-spec copies.
 *
 * The caller must already be on `/admin/settings/universities`.
 */
export async function createUniversityViaUI(
  page: Page,
  name: string,
  factor = '1'
): Promise<void> {
  const dialog = await openCreateDialog(page);

  // Fill name
  await dialog.locator('input').first().fill(name);

  // Fill country autocomplete: type and select the first suggestion.
  // The list is the static countries reference data, so "Ger" must
  // always match (e.g. Germany/Algerien) — a missing suggestion is a
  // product bug and fails the test.
  //
  // The list is fetched from Convex lazily on the first keystroke, so the
  // very first "Ger" races that network round-trip; under parallel staging
  // load the query can take longer than a single keystroke's overlay window
  // and PrimeNG closes the (still-empty) overlay. Re-type until the cached
  // list resolves and the suggestion shows, with a generous overall budget.
  // This does not weaken the check — a real suggestion is still required.
  const countryInput = dialog.locator('p-autocomplete input').first();
  const suggestion = page
    .locator('.p-autocomplete-overlay .p-autocomplete-option, .p-autocomplete-list li')
    .first();
  await expect(
    async () => {
      await countryInput.fill('');
      await countryInput.fill('Ger');
      await expect(
        suggestion,
        'country autocomplete must suggest a match for "Ger" (static country list)'
      ).toBeVisible({ timeout: 3_000 });
    },
    'country autocomplete must suggest a match for "Ger" (static country list)'
  ).toPass({ timeout: 20_000 });
  await suggestion.click();

  // Fill factor (commit via keystrokes + blur — see fillNumberInput)
  const factorInput = dialog.locator('p-inputnumber input').first();
  await expect(factorInput).toBeVisible({ timeout: 5_000 });
  await fillNumberInput(dialog, factorInput, factor);

  await saveDialog(dialog);
}
