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

const __dirname = path.dirname(fileURLToPath(import.meta.url));

/**
 * Document edit history E2E tests.
 * Creates its own test document (two versions) in beforeAll so these tests
 * are fully independent of any other spec file.
 */

let docPath: string;

test.describe('Document history panel', () => {
	test.beforeAll(async ({ browser }) => {
		// Create a fresh browser context that uses the stored auth session
		const context = await browser.newContext({
			storageState: path.join(__dirname, '.auth/user.json'),
			locale: 'de-DE'
		});
		const page = await context.newPage();

		// 1. Create a new document
		await page.goto('/documents/new');
		await page.waitForSelector('[data-hydrated]');
		await page.getByLabel('Titel').fill('E2E History Test Dokument');
		await page.getByRole('button', { name: 'Speichern', exact: true }).click();
		// Wait for redirect to the new document's UUID-based URL (not /documents/new)
		await page.waitForURL(/\/documents\/[0-9a-f-]{36}$/);
		docPath = new URL(page.url()).pathname;

		// 2. Edit the document to create a second version
		await page.goto(`${docPath}/edit`);
		await page.waitForSelector('[data-hydrated]');
		await page.getByLabel('Titel').fill('E2E History Test Dokument (bearbeitet)');
		await page.getByRole('button', { name: 'Speichern', exact: true }).click();
		await page.waitForURL(/\/documents\/[0-9a-f-]{36}$/);

		await context.close();
	});

	test('history section appears and shows two versions', async ({ page }) => {
		await page.goto(docPath);
		await page.waitForSelector('[data-hydrated]');

		const historyToggle = page.getByRole('button', { name: /Verlauf/i });
		await expect(historyToggle).toBeVisible();
		await historyToggle.click();

		// Wait for versions to load (API call happens after panel opens)
		const versionItems = page.locator('[data-testid="history-version"]');
		await expect(versionItems).toHaveCount(2, { timeout: 10000 });

		await page.screenshot({ path: 'test-results/e2e/history-versions-list.png' });
	});

	test('diff view highlights changed field after title edit', async ({ page }) => {
		await page.goto(docPath);
		await page.waitForSelector('[data-hydrated]');

		const historyToggle = page.getByRole('button', { name: /Verlauf/i });
		await historyToggle.click();

		// Wait for versions to load, then click the second one (the edit)
		const versionItems = page.locator('[data-testid="history-version"]');
		await expect(versionItems.nth(1)).toBeVisible({ timeout: 10000 });
		await versionItems.nth(1).click();

		const diffPanel = page.locator('[data-testid="history-diff"]');
		await expect(diffPanel).toBeVisible();
		await expect(diffPanel.getByText(/Titel/i)).toBeVisible();

		await page.screenshot({ path: 'test-results/e2e/history-diff-title.png' });
	});

	test('compare mode lets user compare any two versions', async ({ page }) => {
		await page.goto(docPath);
		await page.waitForSelector('[data-hydrated]');

		const historyToggle = page.getByRole('button', { name: /Verlauf/i });
		await historyToggle.click();

		// Wait for versions to load before the compare button appears
		await expect(page.locator('[data-testid="history-version"]').first()).toBeVisible({
			timeout: 10000
		});

		const compareBtn = page.getByRole('button', { name: /Vergleichen/i });
		await expect(compareBtn).toBeVisible();
		await compareBtn.click();

		const selectA = page.getByLabel(/Version A/i);
		const selectB = page.getByLabel(/Version B/i);
		await expect(selectA).toBeVisible();
		await expect(selectB).toBeVisible();

		// Select version 1 for A and version 2 for B
		await selectA.selectOption({ index: 1 });
		await selectB.selectOption({ index: 2 });

		await page
			.getByRole('button', { name: /Vergleichen/i })
			.last()
			.click();

		const diffPanel = page.locator('[data-testid="history-diff"]');
		await expect(diffPanel).toBeVisible();

		await page.screenshot({ path: 'test-results/e2e/history-compare-mode.png' });
	});
});
