package be.ehealth.businessconnector.test.mycarenet.agreementasyncv2.session;

import be.cin.encrypted.EncryptedKnownContent;
import be.cin.nip.async.generic.MsgResponse;
import be.ehealth.business.mycarenetdomaincommons.domain.InputReference;
import be.ehealth.businessconnector.genericasync.domain.GetRequest;
import be.ehealth.businessconnector.genericasync.domain.ProcessedGetResponse;
import be.ehealth.businessconnector.genericasync.domain.ProcessedMsgResponse;
import be.ehealth.businessconnector.genericasync.domain.ProcessedPostResponse;
import be.ehealth.businessconnector.mycarenet.agreementasync.v2.session.AgreementSessionServiceFactory;
import be.ehealth.technicalconnector.utils.ConnectorIOUtils;
import be.ehealth.technicalconnector.utils.ConnectorXmlUtils;
import be.fgov.ehealth.technicalconnector.tests.utils.XmlAsserter;

import static org.junit.Assert.*;

public abstract class AbstractBaseIntegrationTest {

    protected void getEAgreementResponse(String inputReference) throws Exception {
        byte[] bytes = ConnectorIOUtils.getResourceAsByteArray("/examples/mycarenet/eagreementasyncv2/request/eAgreementRequest.xml");
        ProcessedPostResponse processedPostResponse = AgreementSessionServiceFactory.getAgreementService().getEAgreementRequest(bytes, "200", new InputReference(inputReference), "2.0");
        ProcessedGetResponse<byte[]> response = AgreementSessionServiceFactory.getAgreementService().getEAgreementResponse(GetRequest.newBuilder().withDefaults().build());

        assertEquals("Post response should have success result", "urn:nip:tack:result:major:success", processedPostResponse.getPostResponse().getReturn().getResultMajor());
        assertFalse(response.getMsgResponses().isEmpty());
        ProcessedMsgResponse<byte[]> processedMsgResponse = response.getMsgResponses().get(0);
        assertEquals("SignatureVerificationResult should contain no error", 0, processedMsgResponse.getSignatureVerificationResult().getErrors().size());
        MsgResponse msgResponse = processedMsgResponse.getMsgResponse();
        assertNotNull("Missing xades", msgResponse.getXadesT());
        XmlAsserter.assertSimilar(ConnectorXmlUtils.toObject(processedMsgResponse.getSignedData(), EncryptedKnownContent.class), processedMsgResponse.getRawDecryptedBlob());
        byte[] businessContent = processedMsgResponse.getBusinessResponse();
        String stringContent = new String(businessContent, "UTF-8");
        XmlAsserter.assertSimilar(ConnectorIOUtils.getResourceAsString("/examples/mycarenet/eagreementasyncv2/expected/eAgreementResponse.xml"), stringContent);

        AgreementSessionServiceFactory.getAgreementService().confirmAllMessages(response);
    }
}
