package com.yeejoin.amos.boot.module.jg.biz.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public GlobalExceptionHandler() {
        log.info("GlobalExceptionHandler initialized.");
    }

    @ExceptionHandler(Exception.class)
    public ResponseModel<Object> handleException(Exception exception, HttpServletRequest request) {
        log.error("Exception occurred:", exception);

        ResponseModel<Object> response = new ResponseModel<>();
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setDevMessage("FAILED");
        response.setMessage(exception.getMessage());
        response.setTraceId(RequestContext.getTraceId());
        response.setPath(request != null ? request.getServletPath() : null);

        if (exception.getMessage() != null && (exception.getMessage().contains("账号已经在其他设备登录") || exception.getMessage().contains("请重新登录"))) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
        }
        return response;
    }
}
