package de.assecutor.pdftool.template;

import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

class TemplatePdfServiceTest {

    private final TemplatePdfService service = new TemplatePdfService();

    @Test
    void rendersCanvasTemplateWithVariablesAndPositionsToPdf() {
        String template = """
                {"elements": [
                  {"id": "e1", "type": "text", "variable": "masterdata.company_name",
                   "xPercent": 10, "yPercent": 5, "widthPercent": 40, "heightPercent": 3},
                  {"id": "e2", "type": "text", "text": "Freier Text",
                   "xPercent": 10, "yPercent": 10, "widthPercent": 40, "heightPercent": 3},
                  {"id": "e3", "type": "line", "xPercent": 10, "yPercent": 15, "widthPercent": 80, "heightPercent": 0},
                  {"id": "e4", "type": "text", "variable": "services.list",
                   "xPercent": 10, "yPercent": 20, "widthPercent": 80, "heightPercent": 20}
                ]}""";
        Map<String, String> variables = Map.of(
                "masterdata.company_name", "Assecutor Data Service GmbH",
                "services.json",
                "[{\"name\":\"Beratung\",\"netAmount\":\"100,00\",\"vat\":\"19%\"},"
                        + "{\"name\":\"Fachbuch\",\"netAmount\":\"50,00\",\"vat\":\"7%\"}]",
                "invoice.net_total", "150,00 €",
                "invoice.vat_total", "22,50 €",
                "invoice.gross_total", "172,50 €",
                "invoice.vat_rate", "");

        byte[] pdf = service.generatePdf(template, variables, new BigDecimal("0.19"));

        assertTrue(pdf.length > 500, "PDF sollte Inhalt haben");
        assertArrayEquals("%PDF-".getBytes(StandardCharsets.US_ASCII),
                java.util.Arrays.copyOfRange(pdf, 0, 5), "Ergebnis muss ein PDF sein");
    }

    @Test
    void legacyPixelCoordinatesAreConverted() {
        String template = """
                {"elements": [
                  {"id": "e1", "type": "text", "text": "Legacy", "x": 100, "y": 100, "width": 200, "height": 30}
                ]}""";

        byte[] pdf = service.generatePdf(template, Map.of(), null);

        assertTrue(pdf.length > 500);
    }

    @Test
    void invalidJsonThrowsTemplateRenderException() {
        assertThrows(TemplateRenderException.class,
                () -> service.generatePdf("kein json", Map.of(), null));
    }
}
