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.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.account.service.IMemberTokenService;

/**
 * C 端会员 Token 拦截器
 */
@Component
public class MemberAuthInterceptor implements HandlerInterceptor
{
    private static final String HEADER_TOKEN = "Authorization";

    @Autowired
    private IMemberTokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    {
        String token = resolveToken(request);
        Long memberId = tokenService.getMemberIdByToken(token);
        if (memberId == null)
        {
            throw new ServiceException("请先登录", 401);
        }
        MemberContext.setMemberId(memberId);
        return true;
    }

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

    private String resolveToken(HttpServletRequest request)
    {
        String auth = request.getHeader(HEADER_TOKEN);
        if (StringUtils.isNotEmpty(auth) && auth.startsWith("Bearer "))
        {
            return auth.substring(7);
        }
        String token = request.getHeader("X-Member-Token");
        return StringUtils.isNotEmpty(token) ? token : auth;
    }
}
