package ru.nbch.credit_tracker.utils;

import lombok.extern.slf4j.Slf4j;
import ru.nbch.credit_tracker.entities.user_request.monitoring_request.MonitoringRequest;
import ru.nbch.credit_tracker.entities.user_request.monitoring_request.Subject;
import ru.nbch.credit_tracker.enums.SignalError;
import ru.nbch.credit_tracker.enums.XmlErrorFormat;
import ru.nbch.credit_tracker.exceptions.SignalClientException;

import java.util.regex.Pattern;

import static ru.nbch.credit_tracker.utils.error.ExceptionUtils.clientExcp;

@Slf4j
public class ValidationUtil {

    private static final  String phoneRegex = "^\\d{9}$";
    private static final  String packageNameRegex = "^[A-Z0-9_]{1,22}$";
    private static final  String npIdRegex = "^\\S{1,36}$";

    public static void validateMonitoringRequest(MonitoringRequest request) throws SignalClientException {
        if (request == null) {
            throw clientExcp(SignalError.ERROR_011, XmlErrorFormat.MonitoringError);
        }

        if (request.getPackageName() == null) {
            throw clientExcp(SignalError.ERROR_002, XmlErrorFormat.MonitoringError, "PackageName");
        }

        if (!validatePackageName(request.getPackageName())) {
            throw clientExcp(SignalError.ERROR_008, XmlErrorFormat.MonitoringError);
        }

        if (request.getUserId() == null) {
            throw clientExcp(SignalError.ERROR_002, XmlErrorFormat.MonitoringError, "UserId");
        }

        if (request.getPassword() == null) {
            throw clientExcp(SignalError.ERROR_002, XmlErrorFormat.MonitoringError, "Password");
        }

        if (request.getSubjects() == null) {
            throw clientExcp(SignalError.ERROR_002, XmlErrorFormat.MonitoringError, "Subjects");
        }

        if (request.getSubjects().getSubject().isEmpty()) {
            throw clientExcp(SignalError.ERROR_002, XmlErrorFormat.MonitoringError, "Subject");
        }

        for (Subject subject : request.getSubjects().getSubject()) {
            if (!validateNPId(subject.getId())) {
                throw clientExcp(SignalError.ERROR_010, XmlErrorFormat.MonitoringError, subject.getId());
            }
            if (!validatePhone(subject.getClientId())) {
                throw clientExcp(SignalError.ERROR_003, XmlErrorFormat.MonitoringError, subject.getId());
            }
        }
    }

    private static boolean validatePhone(String input) {
        if(input == null) {
            return false;
        }
        return Pattern.matches(phoneRegex, input);
    }

    private static boolean validatePackageName(String input) {
        if(input == null) {
            return false;
        }
        return Pattern.matches(packageNameRegex, input);
    }

    private static boolean validateNPId(String input) {
        if(input == null) {
            return false;
        }
        return Pattern.matches(npIdRegex, input);
    }
}
