package cn.van.business.controller;

import cn.van.business.model.user.UserInfo;
import cn.van.business.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import java.util.Collections;
import java.util.List;

public class BaseController extends AbstractController {

    @Autowired
    private JwtUtils jwtUtils;

    // 获取当前用户信息
    protected UserInfo getCurrentUser(HttpServletRequest request) {
        String token = extractToken(request);
        if (token != null && jwtUtils.validateToken(token)) {
            String username = jwtUtils.extractUsername(token);
            // 从数据库获取用户信息
            return loadUserInfo(username);
        }
        return null;
    }

    // 检查用户是否已登录
    protected boolean isLogin(HttpServletRequest request) {
        return getCurrentUser(request) != null;
    }

    // 获取当前用户ID
    protected String getCurrentUserId(HttpServletRequest request) {
        UserInfo user = getCurrentUser(request);
        return user != null ? user.getId() : null;
    }

    // 获取当前用户角色
    protected List<String> getCurrentUserRoles(HttpServletRequest request) {
        UserInfo user = getCurrentUser(request);
        return user != null ? user.getRoles() : Collections.emptyList();
    }

    // 提取token
    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    // 加载用户信息
    private UserInfo loadUserInfo(String username) {
        // 实现用户信息加载
        return new UserInfo();
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return null;
    }
}
