package com.firma.api.service;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.*;

@Service
public class FirmaService {

    public Map<String, Object> extraerDatosFirma(MultipartFile archivo) throws Exception {
        Map<String, Object> datos = new HashMap<>();

        try (InputStream inputStream = archivo.getInputStream();
             PDDocument document = PDDocument.load(inputStream)) {

            List<PDSignature> firmas = document.getSignatureDictionaries();

            if (firmas.isEmpty()) {
                datos.put("mensaje", "No se encontraron firmas digitales.");
                return datos;
            }

            PDSignature firma = firmas.get(0);

            byte[] contenidoFirma = firma.getContents(inputStream);
            byte[] signedContent = firma.getSignedContent(inputStream);

            CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(signedContent), contenidoFirma);
            X509CertificateHolder certHolder = (X509CertificateHolder) cms.getCertificates().getMatches(null).iterator().next();

            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) factory.generateCertificate(new java.io.ByteArrayInputStream(certHolder.getEncoded()));

            datos.put("nombre", cert.getSubjectX500Principal().getName());
            datos.put("emisor", cert.getIssuerX500Principal().getName());
            datos.put("validoDesde", cert.getNotBefore());
            datos.put("validoHasta", cert.getNotAfter());
        }

        return datos;
    }
}
