package com.banesco.infrastructure.rest;

import com.banesco.common.domain.model.ApiConfig;
import com.banesco.commons.config.AppConf;
import com.banesco.domain.bian.request.BusUpdateCardStatusRequest;
import com.banesco.domain.models.CurrentState;
import com.banesco.domain.ports.outbound.PaymentCardPort;
import com.banesco.infrastructure.dtos.osb.ApplicantData;
import com.banesco.infrastructure.dtos.osb.MsgRqHdr;
import com.banesco.infrastructure.rest.mappers.PaymentCardMapper;
import com.banesco.infrastructure.rest.mappers.SoapHeaderMapper;
import com.banesco.infrastructure.rest.repositories.PaymentCardRepository;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;


@ApplicationScoped
@Slf4j
public class PaymentCardAdapter implements PaymentCardPort {


    private final PaymentCardRepository paymentRepository;
    private final PaymentCardMapper paymentCardMapper;

    private final SoapHeaderMapper soapHeaderMapper;

    private final String OPERATION_NAME = "update-card-status";
    AppConf appConf;

    @Inject
    public PaymentCardAdapter(AppConf appConf,
                              PaymentCardMapper paymentCardMapper,
                              SoapHeaderMapper soapHeaderMapper
    ) {

        this.appConf = appConf;
        this.paymentCardMapper = paymentCardMapper;
        this.soapHeaderMapper = soapHeaderMapper;
        ApiConfig apiConfig = appConf.loadApiConfig("api.rest-client." + OPERATION_NAME + ".endpoint");
        paymentRepository = new PaymentCardRepository(apiConfig);

    }


    public void updateCardStatus(String clearAccount, BusUpdateCardStatusRequest request) {

        CurrentState currentState = appConf.getCurrentState(request.getRequestId());

        MsgRqHdr msgRqHdr = soapHeaderMapper.getHeaderBySrcAppId(
                OPERATION_NAME,
                currentState
        );


        if (msgRqHdr.getApplicantData() == null) {
            msgRqHdr.setApplicantData(new ApplicantData());
        }

        msgRqHdr.getApplicantData().setIpAddress(request.getDevice().getDeviceIp());


        paymentRepository.updateCardStatus(
                request.getRequestId(),
                this.paymentCardMapper.toBusinessRequest(
                        msgRqHdr,
                        request,
                        clearAccount,
                        appConf.getSoapDomainCurrent()
                )

        );


    }


}
