import type { APIRequestContext } from '@playwright/test';

/**
 * Test fixture for the briefwechsel row layout.
 *
 * Creates two persons and one document with sender/receiver between them so
 * that `/briefwechsel?senderId=X&receiverId=Y` navigates straight to the row
 * state (not the hero). Each seed uses a `Date.now()`-suffixed last name so
 * parallel runs and reruns never collide.
 *
 * The backend does not expose a person-delete endpoint, so only the document
 * is cleaned up in {@link cleanupBilateralPair}. The two timestamped persons
 * remain in the DB — acceptable for the test environment, and the unique
 * suffix means they cannot conflict with later runs.
 */

export interface BilateralPair {
	senderId: string;
	receiverId: string;
	documentId: string;
}

export async function seedBilateralPair(
	request: APIRequestContext,
	prefix: string
): Promise<BilateralPair> {
	const timestamp = Date.now();

	const senderRes = await request.post('/api/persons', {
		data: { firstName: prefix, lastName: `Sender-${timestamp}` }
	});
	if (!senderRes.ok()) throw new Error(`Create sender failed: ${senderRes.status()}`);
	const senderId = (await senderRes.json()).id as string;

	const receiverRes = await request.post('/api/persons', {
		data: { firstName: prefix, lastName: `Receiver-${timestamp}` }
	});
	if (!receiverRes.ok()) throw new Error(`Create receiver failed: ${receiverRes.status()}`);
	const receiverId = (await receiverRes.json()).id as string;

	const docRes = await request.post('/api/documents', {
		multipart: {
			title: `${prefix} Brief`,
			documentDate: '1950-06-15',
			senderId,
			receiverIds: receiverId
		}
	});
	if (!docRes.ok()) throw new Error(`Create document failed: ${docRes.status()}`);
	const documentId = (await docRes.json()).id as string;

	return { senderId, receiverId, documentId };
}

export async function cleanupBilateralPair(
	request: APIRequestContext,
	pair: BilateralPair
): Promise<void> {
	// Only the document is purged — the backend has no person-delete endpoint
	// and the timestamped last names make orphaned person rows safe to leave.
	await request.delete(`/api/documents/${pair.documentId}`);
}
