package com.devjob.common.exception;

import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

/**
 * EP10: 모든 서비스의 에러 응답을 동일한 형태로 통일한다.
 * { success: false, errorCode: "MEMBER_NOT_FOUND", message: "...", errors: { field: reason } }
 */
public record ErrorResponse(
        boolean success,
        String errorCode,
        String message,
        Map<String, String> errors
) {
    public static ErrorResponse of(ErrorCode errorCode) {
        return new ErrorResponse(false, errorCode.name(), errorCode.getMessage(), null);
    }

    public static ErrorResponse validationError(MethodArgumentNotValidException ex) {
        Map<String, String> fieldErrors = new LinkedHashMap<>();
        for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
            fieldErrors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return new ErrorResponse(false, ErrorCode.VALIDATION_ERROR.name(), ErrorCode.VALIDATION_ERROR.getMessage(), fieldErrors);
    }
}
