package application.factory;

import application.port.input.command.RegisterSecurityCommand;
import domain.dto.response.StatusResponse;
import domain.model.AccountClientContext;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Slf4j
@ApplicationScoped
public class SecurityTraceFactory {

    public RegisterSecurityCommand createCommandFromContext(AccountClientContext context, StatusResponse statusResponse) {
        var request = context.getRequest();
        var customerReference = request.getCustomerPositionState().getCustomerReference();
        var device = request.getDevice();

        long durationInMillis = System.currentTimeMillis() - context.getStartExecution();

        return RegisterSecurityCommand.builder()
                .login(context.getUsername())
                .fecHor(Timestamp.valueOf(LocalDateTime.now()))
                .nacCli(customerReference.getCustomerIdType())
                .cedRifCli(Integer.valueOf(customerReference.getCustomerId()))
                .tipoRespuesta(Integer.valueOf(statusResponse.getStatusCode()))
                .msgRespuesta(statusResponse.getMessage())
                .codFintech(context.getFintechId())
                .tiempoRespuesta((int) durationInMillis)
                .tipoDispositivo(device.getDeviceType())
                .desDispositivo(device.getDeviceDescription())
                .ipCli(device.getDeviceIp())
                .build();
    }
}