import { expect, test } from '@playwright/test';

/**
 * Auto-title sync, full-stack happy path (#726). A document whose stored title equals its
 * machine-generated auto-title must follow a date correction forward on save; a hand-edit would
 * be kept. The exhaustive permutations live in the backend unit/integration suites — this is the
 * single end-to-end pass, and it also asserts the FR-005 helper line is present on the edit form.
 */
test.describe('Document auto-title sync (#726)', () => {
	test('editing the date rebuilds the auto-title, and the edit form explains it', async ({
		page
	}) => {
		// 1. Create a document with no date/location, so its stored title == its auto-title
		//    (originalFilename only). createDocument derives originalFilename from the title.
		await page.goto('/documents/new');
		await page.waitForSelector('[data-hydrated]');
		await page.getByLabel('Titel').fill('E2E Auto-Titel Sync');
		await page.getByRole('button', { name: 'Speichern', exact: true }).click();
		await expect(page).toHaveURL(/\/documents\/[^/]+$/);
		const detailUrl = page.url();

		// 2. The edit form carries the FR-005 helper explaining the auto-generated title.
		await page.goto(`${detailUrl}/edit`);
		await page.waitForSelector('[data-hydrated]');
		await expect(page.locator('#title-help')).toBeVisible();

		// 3. Add a YEAR-precision date WITHOUT touching the title, then save.
		await page.locator('#documentDate').fill('15.01.1928');
		await page.locator('#documentDatePrecision').selectOption('YEAR');
		await page.getByRole('button', { name: 'Speichern', exact: true }).click();

		// 4. The detail page shows the regenerated title carrying the new year.
		await expect(page).toHaveURL(/\/documents\/[^/]+$/);
		await expect(page.getByRole('heading', { name: /E2E Auto-Titel Sync.*1928/ })).toBeVisible();
	});
});
