package com.arms.api.util.errors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.reactive.function.client.WebClientResponseException;

@Slf4j
public class ErrorLogUtil {

    public static void exceptionLogging(Exception e, String className, String methodName) {
        String errorMessage = generateErrorMessage(e, className, methodName);
        log.error(errorMessage);
    }

    public static String exceptionLoggingAndReturn(Exception e, String className, String methodName) {
        String errorMessage = generateErrorMessage(e, className, methodName);
        log.error(errorMessage);
        return errorMessage;
    }

    private static String generateErrorMessage(Exception e, String className, String methodName) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append(" [ ")
                .append(className)
                .append(" :: ")
                .append(methodName)
                .append(" ] :: ")
                .append(e.getClass().getName())
                .append(" :: ")
                .append(e.getMessage());

        if (e instanceof WebClientResponseException) {
            WebClientResponseException wcException = (WebClientResponseException) e;
            HttpStatusCode status = wcException.getStatusCode();
            String body = wcException.getResponseBodyAsString();

            errorMessage.append(" :: ")
                    .append(status)
                    .append(" :: ")
                    .append(body);
        }

        return errorMessage.toString();
    }
}
