package com.banesco.common.application.helper;

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

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

    private static final String REQUIRED_CODE = "VDE01";
    private static final String VALIDATE_CODE = "VDE02";

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

    public void validateRequired(
        DocserviceFileAuditTraceRequest request
    ) {
        required(request.getDocumentName(), "document.documentName");
        required(request.getDocumentDirectory(), "document.documentLocation[0].locationReference.locationValue");
        required(request.getChannelCode(), "procedureRequest.instructionPurposeType");
        required(request.getCustomerReferenceFintechId(), "customerReferenceFintechId");
        required(request.getAppId(), "appId");
    }

    public void validateFieldValues(
        DocserviceFileAuditTraceRequest request
    ) {
        validate(request.getDocumentName(), config.documentName(), "document.documentName");
        validate(request.getChannelCode(), config.channelCode(), "procedureRequest.instructionPurposeType");
    }

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

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