package de.gecheckt.pdf.umbenenner.bootstrap.e2e;

import java.io.IOException;
import java.nio.file.Path;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;

/**
 * Factory for creating minimal PDF test fixtures used in end-to-end tests.
 * <p>
 * Provides two variants:
 * <ul>
 *   <li>Searchable PDFs with embedded text content — used for happy-path, transient-error,
 *       and target-copy-failure scenarios where the pre-check must pass.</li>
 *   <li>Blank PDFs with no extractable text — used for deterministic content-error
 *       scenarios where the pre-check must fail.</li>
 * </ul>
 * <p>
 * Uses Apache PDFBox to create real, structurally valid PDF files so that the
 * production {@code PdfTextExtractionPortAdapter} processes them correctly.
 */
final class MinimalPdfFactory {

    private MinimalPdfFactory() {
        // Static utility class — not instantiable
    }

    /**
     * Creates a single-page searchable PDF with the given text content at the output path.
     * <p>
     * The resulting file passes the production pre-checks for minimum text length and
     * page count, enabling the AI naming pipeline to run.
     *
     * @param outputPath  the path where the PDF will be written; parent directory must exist
     * @param textContent the text to embed in the PDF; should be non-empty for happy-path tests
     * @throws IOException if the file cannot be written
     */
    static void createSearchablePdf(Path outputPath, String textContent) throws IOException {
        try (PDDocument doc = new PDDocument()) {
            PDPage page = new PDPage();
            doc.addPage(page);
            try (PDPageContentStream stream = new PDPageContentStream(doc, page)) {
                stream.beginText();
                stream.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
                stream.newLineAtOffset(50, 700);
                stream.showText(textContent);
                stream.endText();
            }
            doc.save(outputPath.toFile());
        }
    }

    /**
     * Creates a single-page blank PDF with no text content at the output path.
     * <p>
     * The resulting file triggers the "no usable text" pre-check failure
     * (deterministic content error), which does not invoke the AI service.
     *
     * @param outputPath the path where the PDF will be written; parent directory must exist
     * @throws IOException if the file cannot be written
     */
    static void createBlankPdf(Path outputPath) throws IOException {
        try (PDDocument doc = new PDDocument()) {
            doc.addPage(new PDPage());
            doc.save(outputPath.toFile());
        }
    }
}
