package de.assecutor.pdftool.template;

import de.assecutor.pdftool.invoice.InvoiceMetadata;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class TemplateVariablesTest {

    private static InvoiceMetadata.LineItem item(String description, String quantity, String unitPrice, String vat) {
        return new InvoiceMetadata.LineItem(description, new BigDecimal(quantity), new BigDecimal(unitPrice),
                new BigDecimal(vat));
    }

    @Test
    void addPositionsComputesTotalsFromQuantityAndUnitPrice() {
        Map<String, String> variables = new HashMap<>();

        TemplateVariables.addPositions(variables, List.of(
                item("Beratung", "2", "100.00", "19"),
                item("Fachbuch", "1", "50.00", "19")));

        assertEquals("250,00 €", variables.get("invoice.net_total"));
        assertEquals("47,50 €", variables.get("invoice.vat_total"));
        assertEquals("297,50 €", variables.get("invoice.gross_total"));
        assertEquals("19%", variables.get("invoice.vat_rate"));
        assertEquals("2", variables.get("services.count"));
        assertTrue(variables.get("services.json").contains("\"netAmount\":\"200,00\""),
                "Nettobetrag der Position muss Menge x Einzelpreis sein");
    }

    @Test
    void mixedVatRatesYieldEmptyUniformLabelAndPerRowVat() {
        Map<String, String> variables = new HashMap<>();

        TemplateVariables.addPositions(variables, List.of(
                item("Beratung", "1", "100.00", "19"),
                item("Fachbuch", "1", "50.00", "7")));

        assertEquals("", variables.get("invoice.vat_rate"));
        assertEquals("22,50 €", variables.get("invoice.vat_total"));
        assertTrue(variables.get("services.json").contains("\"vat\":\"19%\""));
        assertTrue(variables.get("services.json").contains("\"vat\":\"7%\""));
    }

    @Test
    void canvasPositionsJsonContainsRowsAndTotals() {
        String json = TemplateVariables.canvasPositionsJson(List.of(item("Beratung", "1", "100.00", "19")));

        assertTrue(json.contains("\"rows\""));
        assertTrue(json.contains("\"netTotal\":\"100,00 €\""));
        assertTrue(json.contains("\"grossTotal\":\"119,00 €\""));
    }
}
