package com.ttstd.signaling.controller;

import com.ttstd.signaling.security.AuthException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 统一异常处理：仅向客户端返回模糊提示，详细原因只记录在服务端日志，
 * 避免通过错误信息差异探测账号是否存在、设备是否在线等。
 */
@RestControllerAdvice
public class AuthExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(AuthExceptionHandler.class);

    @ExceptionHandler(AuthException.class)
    public ResponseEntity<Map<String, Object>> handleAuth(AuthException ex) {
        logger.warn("认证/授权失败 [{}]: {}", ex.getCode(), ex.getMessage());
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("code", ex.getStatus());
        body.put("error", ex.getCode());
        body.put("message", ex.getPublicMessage());
        return ResponseEntity.status(ex.getStatus()).body(body);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidation(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getFieldErrors().stream()
                .findFirst()
                .map(e -> e.getDefaultMessage())
                .orElse("请求参数不合法");
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("code", 400);
        body.put("error", "BAD_REQUEST");
        body.put("message", message);
        return ResponseEntity.badRequest().body(body);
    }
}
