package com.lesingle.common.exception;

import com.lesingle.common.enums.ErrorCode;
import com.lesingle.common.result.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /** 业务异常 */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常，路径：{}，消息：{}", request.getRequestURI(), e.getMessage());
        return Result.error(e.getCode(), e.getMessage(), request.getRequestURI());
    }

    /** 参数校验异常（@Valid） */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleValidationException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining(", "));
        log.warn("参数校验失败，路径：{}，消息：{}", request.getRequestURI(), message);
        return Result.error(400, message, request.getRequestURI());
    }

    /** 参数绑定异常 */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleBindException(BindException e, HttpServletRequest request) {
        String message = e.getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining(", "));
        log.warn("参数绑定失败，路径：{}，消息：{}", request.getRequestURI(), message);
        return Result.error(400, message, request.getRequestURI());
    }

    /** 认证异常 */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Void> handleAuthenticationException(AuthenticationException e, HttpServletRequest request) {
        return Result.error(401, ErrorCode.UNAUTHORIZED.getMessage(), request.getRequestURI());
    }

    /** 授权异常 */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result<Void> handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        return Result.error(403, ErrorCode.FORBIDDEN.getMessage(), request.getRequestURI());
    }

    /** 资源不存在 */
    @ExceptionHandler(NoResourceFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result<Void> handleNotFoundException(NoResourceFoundException e, HttpServletRequest request) {
        return Result.error(404, ErrorCode.NOT_FOUND.getMessage(), request.getRequestURI());
    }

    /** 数据完整性违反（唯一约束冲突） */
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public Result<Void> handleDataIntegrityViolation(DataIntegrityViolationException e, HttpServletRequest request) {
        String message = parseDuplicateMessage(e);
        log.warn("数据冲突，路径：{}，消息：{}", request.getRequestURI(), message);
        return Result.error(409, message, request.getRequestURI());
    }

    /** 主键/唯一键重复（MySQL 驱动可能直接抛此异常） */
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public Result<Void> handleDuplicateKey(DuplicateKeyException e, HttpServletRequest request) {
        String message = parseDuplicateMessage(e);
        log.warn("唯一键冲突，路径：{}，消息：{}", request.getRequestURI(), message);
        return Result.error(409, message, request.getRequestURI());
    }

    /** 兜底：未知异常 */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常，路径：{}，消息：{}", request.getRequestURI(), e.getMessage(), e);
        return Result.error(500, ErrorCode.INTERNAL_ERROR.getMessage(), request.getRequestURI());
    }

    /**
     * 解析数据库唯一约束冲突的具体字段，返回友好提示
     */
    private String parseDuplicateMessage(Exception e) {
        String rootMsg = getRootCauseMessage(e);
        if (rootMsg == null) {
            return ErrorCode.CONFLICT.getMessage();
        }
        String lowerMsg = rootMsg.toLowerCase();
        if (lowerMsg.contains("phone")) {
            return ErrorCode.USER_PHONE_DUPLICATE.getMessage();
        }
        if (lowerMsg.contains("username")) {
            return ErrorCode.USER_DUPLICATE.getMessage();
        }
        return ErrorCode.CONFLICT.getMessage();
    }

    /**
     * 获取异常链中的根因消息
     */
    private String getRootCauseMessage(Throwable e) {
        Throwable cause = e;
        while (cause.getCause() != null) {
            cause = cause.getCause();
        }
        return cause.getMessage();
    }
}
