package com.qaup.collision.common.exception;

import com.qaup.collision.common.model.dto.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 无人车控制异常处理器
 * 
 * 统一处理无人车控制相关的异常，包括：
 * - 参数验证异常
 * - 业务逻辑异常
 * - 数据访问异常
 * - 外部API调用异常
 */
@ControllerAdvice
@Slf4j
public class VehicleControlExceptionHandler {

    /**
     * 处理无人车控制指令异常
     */
    @ExceptionHandler(VehicleCommandException.class)
    public ResponseEntity<Response<Object>> handleVehicleCommandException(VehicleCommandException ex) {
        log.error("无人车控制指令异常: {}", ex.getMessage(), ex);
        
        Response<Object> response = Response.error(
            ex.getErrorCode() != null ? ex.getErrorCode() : 400,
            ex.getMessage()
        );
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    /**
     * 处理无人车位置信息异常
     */
    @ExceptionHandler(VehicleLocationException.class)
    public ResponseEntity<Response<Object>> handleVehicleLocationException(VehicleLocationException ex) {
        log.error("无人车位置信息异常: {}", ex.getMessage(), ex);
        
        Response<Object> response = Response.error(
            ex.getErrorCode() != null ? ex.getErrorCode() : 400,
            ex.getMessage()
        );
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    /**
     * 处理无人车状态查询异常
     */
    @ExceptionHandler(VehicleStateException.class)
    public ResponseEntity<Response<Object>> handleVehicleStateException(VehicleStateException ex) {
        log.error("无人车状态查询异常: {}", ex.getMessage(), ex);
        
        Response<Object> response = Response.error(
            ex.getErrorCode() != null ? ex.getErrorCode() : 400,
            ex.getMessage()
        );
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    /**
     * 处理参数验证异常 - @Valid注解触发
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Response<Object>> handleValidationException(MethodArgumentNotValidException ex) {
        log.warn("参数验证失败: {}", ex.getMessage());
        
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        
        String errorMessage = "参数验证失败: " + errors.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining(", "));
        
        Response<Object> response = Response.error(400, errorMessage);
        response.setData(errors);
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<Response<Object>> handleBindException(BindException ex) {
        log.warn("参数绑定失败: {}", ex.getMessage());
        
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        
        String errorMessage = "参数绑定失败: " + errors.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining(", "));
        
        Response<Object> response = Response.error(400, errorMessage);
        response.setData(errors);
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    /**
     * 处理约束验证异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Response<Object>> handleConstraintViolationException(ConstraintViolationException ex) {
        log.warn("约束验证失败: {}", ex.getMessage());
        
        Map<String, String> errors = new HashMap<>();
        for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
            String fieldName = violation.getPropertyPath().toString();
            String errorMessage = violation.getMessage();
            errors.put(fieldName, errorMessage);
        }
        
        String errorMessage = "约束验证失败: " + errors.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining(", "));
        
        Response<Object> response = Response.error(400, errorMessage);
        response.setData(errors);
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    /**
     * 处理数据访问异常
     */
    @ExceptionHandler(DataAccessException.class)
    public ResponseEntity<Response<Object>> handleDataAccessException(DataAccessException ex) {
        log.error("数据访问异常: {}", ex.getMessage(), ex);
        
        Response<Object> response = Response.error(500, "数据访问失败，请稍后重试");
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }

    /**
     * 处理外部API调用异常
     */
    @ExceptionHandler(ExternalApiException.class)
    public ResponseEntity<Response<Object>> handleExternalApiException(ExternalApiException ex) {
        log.error("外部API调用异常: {}", ex.getMessage(), ex);
        
        Response<Object> response = Response.error(
            ex.getErrorCode() != null ? ex.getErrorCode() : 502,
            "外部服务调用失败: " + ex.getMessage()
        );
        
        return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(response);
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Response<Object>> handleIllegalArgumentException(IllegalArgumentException ex) {
        log.warn("非法参数异常: {}", ex.getMessage());
        
        Response<Object> response = Response.error(400, "参数错误: " + ex.getMessage());
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<Response<Object>> handleNullPointerException(NullPointerException ex) {
        log.error("空指针异常: {}", ex.getMessage(), ex);
        
        Response<Object> response = Response.error(500, "系统内部错误，请联系管理员");
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Response<Object>> handleRuntimeException(RuntimeException ex) {
        log.error("运行时异常: {}", ex.getMessage(), ex);
        
        Response<Object> response = Response.error(500, "系统运行异常: " + ex.getMessage());
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }

    /**
     * 处理通用异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Response<Object>> handleGenericException(Exception ex) {
        log.error("未处理的异常: {}", ex.getMessage(), ex);
        
        Response<Object> response = Response.error(500, "系统异常，请稍后重试");
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }

    /**
     * 无人车控制指令异常
     */
    public static class VehicleCommandException extends RuntimeException {
        private Integer errorCode;
        
        public VehicleCommandException(String message) {
            super(message);
        }
        
        public VehicleCommandException(String message, Throwable cause) {
            super(message, cause);
        }
        
        public VehicleCommandException(Integer errorCode, String message) {
            super(message);
            this.errorCode = errorCode;
        }
        
        public VehicleCommandException(Integer errorCode, String message, Throwable cause) {
            super(message, cause);
            this.errorCode = errorCode;
        }
        
        public Integer getErrorCode() {
            return errorCode;
        }
    }

    /**
     * 无人车位置信息异常
     */
    public static class VehicleLocationException extends RuntimeException {
        private Integer errorCode;
        
        public VehicleLocationException(String message) {
            super(message);
        }
        
        public VehicleLocationException(String message, Throwable cause) {
            super(message, cause);
        }
        
        public VehicleLocationException(Integer errorCode, String message) {
            super(message);
            this.errorCode = errorCode;
        }
        
        public VehicleLocationException(Integer errorCode, String message, Throwable cause) {
            super(message, cause);
            this.errorCode = errorCode;
        }
        
        public Integer getErrorCode() {
            return errorCode;
        }
    }

    /**
     * 无人车状态查询异常
     */
    public static class VehicleStateException extends RuntimeException {
        private Integer errorCode;
        
        public VehicleStateException(String message) {
            super(message);
        }
        
        public VehicleStateException(String message, Throwable cause) {
            super(message, cause);
        }
        
        public VehicleStateException(Integer errorCode, String message) {
            super(message);
            this.errorCode = errorCode;
        }
        
        public VehicleStateException(Integer errorCode, String message, Throwable cause) {
            super(message, cause);
            this.errorCode = errorCode;
        }
        
        public Integer getErrorCode() {
            return errorCode;
        }
    }

    /**
     * 数据访问异常
     */
    public static class DataAccessException extends RuntimeException {
        public DataAccessException(String message) {
            super(message);
        }
        
        public DataAccessException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    /**
     * 外部API调用异常
     */
    public static class ExternalApiException extends RuntimeException {
        private Integer errorCode;
        
        public ExternalApiException(String message) {
            super(message);
        }
        
        public ExternalApiException(String message, Throwable cause) {
            super(message, cause);
        }
        
        public ExternalApiException(Integer errorCode, String message) {
            super(message);
            this.errorCode = errorCode;
        }
        
        public ExternalApiException(Integer errorCode, String message, Throwable cause) {
            super(message, cause);
            this.errorCode = errorCode;
        }
        
        public Integer getErrorCode() {
            return errorCode;
        }
    }
} 