package com.corewing.app.handler;

import cn.dev33.satoken.exception.NotLoginException;
import com.corewing.app.common.Result;
import com.corewing.app.util.I18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

    /**
     * 处理 Sa-Token 未登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<String> handleNotLoginException(NotLoginException e) {
        // 根据不同的场景返回不同的提示
        String message;
        switch (e.getType()) {
            case NotLoginException.NOT_TOKEN:
                message = I18nUtil.getMessage("error.token.missing");
                break;
            case NotLoginException.INVALID_TOKEN:
                message = I18nUtil.getMessage("error.token.invalid");
                break;
            case NotLoginException.TOKEN_TIMEOUT:
                message = I18nUtil.getMessage("error.token.expired");
                break;
            case NotLoginException.BE_REPLACED:
                message = I18nUtil.getMessage("error.token.replaced");
                break;
            case NotLoginException.KICK_OUT:
                message = I18nUtil.getMessage("error.token.kicked.out");
                break;
            default:
                message = I18nUtil.getMessage("error.not.login");
        }
        return Result.error(HttpStatus.UNAUTHORIZED.value(), message);
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> handleException(Exception e) {
        log.error(e.getMessage());
        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
            I18nUtil.getMessage("error.server.internal", e.getMessage()));
    }
}
