package com.ruoyi.web.modules.account.support;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.framework.web.service.TokenService;

/**
 * C 端会员 Token 拦截器（与平台一致：解析 JWT + Redis 中的 LoginUser）
 */
@Component
public class MemberAuthInterceptor implements HandlerInterceptor
{
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser == null || loginUser.getUserId() == null)
        {
            throw new ServiceException("请先登录", 401);
        }
        MemberContext.setMemberId(loginUser.getUserId());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex)
    {
        MemberContext.clear();
    }

}
