package at.procon.eventhub.tachographfilesession.service;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import org.junit.jupiter.api.Test;

class TachographXmlParserTest {

    private final TachographXmlParser parser = new TachographXmlParser();

    @Test
    void parsesValidDriverCardXml() {
        TachographXmlParser.ParsedTachographXml parsed = parser.parse(DriverCardXmlSamples.validDriverCardXml());

        assertThat(parsed.rootElementName()).isEqualTo("DriverCard");
        assertThat(parsed.document().getDocumentElement().getNodeName()).isEqualTo("DriverCard");
    }

    @Test
    void parsesValidVehicleUnitXml() {
        TachographXmlParser.ParsedTachographXml parsed = parser.parse("<VehicleUnit/>");

        assertThat(parsed.rootElementName()).isEqualTo("VehicleUnit");
        assertThat(parsed.document().getDocumentElement().getNodeName()).isEqualTo("VehicleUnit");
    }

    @Test
    void parsesXmlWithLeadingUtf8BomCharacter() {
        String xmlWithBom = "\uFEFF" + DriverCardXmlSamples.validDriverCardXml();

        TachographXmlParser.ParsedTachographXml parsed = parser.parse(xmlWithBom);

        assertThat(parsed.rootElementName()).isEqualTo("DriverCard");
        assertThat(parsed.document().getDocumentElement().getNodeName()).isEqualTo("DriverCard");
    }

    @Test
    void rejectsInvalidXmlAgainstSchema() {
        String invalid = "<DriverCard><Identification></DriverCard>";

        assertThatThrownBy(() -> parser.parse(invalid))
                .isInstanceOf(TachographXmlValidationException.class);
    }

    @Test
    void rejectsXmlWithDoctype() {
        String xmlWithDoctype = """
                <!DOCTYPE DriverCard [
                  <!ELEMENT DriverCard ANY>
                ]>
                <DriverCard/>
                """;

        assertThatThrownBy(() -> parser.parse(xmlWithDoctype))
                .isInstanceOf(TachographXmlValidationException.class);
    }
}
