package dev.lions.unionflow.server.payment.pispi.dto;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.time.Instant;

public class Pacs002Response {

    private String originalMessageId;
    private String originalEndToEndId;
    private String transactionStatus;
    private String rejectReasonCode;
    private String clearingSystemReference;
    private Instant acceptanceDateTime;

    public Pacs002Response() {}

    public String getOriginalMessageId() { return originalMessageId; }
    public void setOriginalMessageId(String originalMessageId) { this.originalMessageId = originalMessageId; }

    public String getOriginalEndToEndId() { return originalEndToEndId; }
    public void setOriginalEndToEndId(String originalEndToEndId) { this.originalEndToEndId = originalEndToEndId; }

    public String getTransactionStatus() { return transactionStatus; }
    public void setTransactionStatus(String transactionStatus) { this.transactionStatus = transactionStatus; }

    public String getRejectReasonCode() { return rejectReasonCode; }
    public void setRejectReasonCode(String rejectReasonCode) { this.rejectReasonCode = rejectReasonCode; }

    public String getClearingSystemReference() { return clearingSystemReference; }
    public void setClearingSystemReference(String clearingSystemReference) { this.clearingSystemReference = clearingSystemReference; }

    public Instant getAcceptanceDateTime() { return acceptanceDateTime; }
    public void setAcceptanceDateTime(Instant acceptanceDateTime) { this.acceptanceDateTime = acceptanceDateTime; }

    public static Pacs002Response fromXml(String xml) {
        Pacs002Response response = new Pacs002Response();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false);
            // Désactiver les entités externes (OWASP XXE)
            factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xml)));
            doc.getDocumentElement().normalize();

            response.setOriginalEndToEndId(firstText(doc, "OrgnlEndToEndId"));
            response.setTransactionStatus(firstText(doc, "TxSts"));
            response.setRejectReasonCode(firstText(doc, "RsnCd"));
            response.setClearingSystemReference(firstText(doc, "ClrSysRef"));

            String acptDtTm = firstText(doc, "AccptncDtTm");
            if (acptDtTm != null && !acptDtTm.isBlank()) {
                try {
                    response.setAcceptanceDateTime(Instant.parse(acptDtTm));
                } catch (Exception ignored) {
                    // format non parsable — on laisse null
                }
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("Impossible de parser le pacs.002 XML : " + e.getMessage(), e);
        }
        return response;
    }

    private static String firstText(Document doc, String tagName) {
        NodeList nodes = doc.getElementsByTagName(tagName);
        if (nodes.getLength() > 0) {
            String text = nodes.item(0).getTextContent();
            return (text == null || text.isBlank()) ? null : text.trim();
        }
        return null;
    }
}
