package com.banesco.common.application.helper;

import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.common.infrastructure.config.RequestValidationConfig;
import com.banesco.module.correspondence.domain.dto.request.CorrespondenceRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;

@Slf4j
@ApplicationScoped
public class RequestValidatorHelper {
    private final RequestValidationConfig config;

    @Inject
    public RequestValidatorHelper(
        RequestValidationConfig config
    ) {
        this.config = config;
    }

    public void validateRequired(
        CorrespondenceRequest request
    ) {
        required(request.getCodeType(), "correspondenceOutbound.sourceReference");
        required(request.getRecipientId(), "correspondenceOutbound.customerReference.partyIdentification[0].partyIdentification.identifierValue");
        required(request.getCustomerReferenceFintechId(), "customerReferenceFintechId");
        required(request.getAppId(), "appId");
    }

    public void validateFieldValues(
        CorrespondenceRequest request
    ) {
        validate(request.getRecipientId(), config.recipientIdNumber(), "correspondenceOutbound.customerReference.partyIdentification[0].partyIdentification.identifierValue");
        validate(request.getAmount(), "paymentInstruction.amount[0].value");
        validate(request.getChannelCode(), config.channelCode(), "channelCode");
    }

    private void required(String value, String fieldName) {
        if (value == null || value.trim().isEmpty()) {
            throw HttpStatusCodeException.badRequest("VDE01", fieldName);
        }
    }

    private void required(BigDecimal value, String fieldName) {
        if (value == null) {
            throw HttpStatusCodeException.badRequest("VDE01", fieldName);
        }
    }

    private void validate(String value, String regex, String fieldName) {
        if (value != null && !value.isEmpty() && !value.matches(regex)) {
            throw HttpStatusCodeException.badRequest("VDE02", fieldName);
        }
    }

    private void validate(BigDecimal value, String fieldName) {
        if (value != null && value.compareTo(BigDecimal.ZERO) < 1) {
            throw HttpStatusCodeException.badRequest("VDE02", fieldName);
        }
    }
}
