import type { APIRequestContext } from '@playwright/test';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PDF_FIXTURE = path.resolve(__dirname, '../fixtures/minimal.pdf');

export async function createEmptyDocument(request: APIRequestContext): Promise<string> {
	const createRes = await request.post('/api/documents', {
		multipart: { title: 'E2E Transcribe Coach Test' }
	});
	if (!createRes.ok()) throw new Error(`Create document failed: ${createRes.status()}`);
	const doc = await createRes.json();
	const docId = doc.id as string;

	const uploadRes = await request.put(`/api/documents/${docId}`, {
		multipart: {
			title: doc.title,
			file: {
				name: 'minimal.pdf',
				mimeType: 'application/pdf',
				buffer: fs.readFileSync(PDF_FIXTURE)
			}
		}
	});
	if (!uploadRes.ok()) throw new Error(`Upload PDF failed: ${uploadRes.status()}`);

	return docId;
}
