package com.banesco.module.msg_request_header.domain.model;

import com.banesco.common.domain.model.Device;
import com.banesco.common.infrastructure.context.RequestContext;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@Getter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@RegisterForReflection
public class MsgRqHdr {
    private String messageDate;
    private String messageTime;
    private String requestId;
    private String lastStatusRequest;
    private String finalStatusRequest;
    private String resumeId;
    private String reverseId;
    private String lineId;
    private String sourceChannelCode;
    private String supervisorCode;
    private String operatorCode;
    private String requestedOperationType;
    private List<NetworkTrnInfo> networkTrnInfo;
    private ApplicantData applicantData;
    private RecCtrlIn recCtrlIn;
    private String returnValue;
    private String messageId;
    private String priority;
    private VbProtocol vbProtocol;

    private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @JsonIgnore
    public MsgRqHdr withOptions(Device device) {
        if(Objects.isNull(this.getApplicantData())) {
            this.applicantData = ApplicantData.builder()
                .ipAddress(device.getDeviceIp())
                .build();
        } else {
            this.applicantData = this.applicantData.withOptions(device);
        }

        String[] dateTime = LocalDateTime.now().format(dateTimeFormatter).split(" ");
        String date = dateTime[0];
        String time = dateTime[1];

        this.requestId = RequestContext.getRequestId();
        this.messageDate = date;
        this.messageTime = time;

        this.networkTrnInfo = this.networkTrnInfo.stream()
            .map(info -> (!Objects.isNull(info)) ? info.withOptions(date, time) : null)
            .toList();

        return this;
    }
}
