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.
  const countryInput = dialog.locator('p-autocomplete input').first();
  await countryInput.fill('Ger');
  const suggestion = page
    .locator('.p-autocomplete-overlay .p-autocomplete-option, .p-autocomplete-list li')
    .first();
  await expect(
    suggestion,
    'country autocomplete must suggest a match for "Ger" (static country list)'
  ).toBeVisible({ timeout: 5_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);
}
