package cn.skcks.matrix.v2.auth.claims;

import cn.skcks.matrix.v2.model.jwt.dto.Claims;
import cn.skcks.matrix.v2.services.jwt.JwtService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Slf4j
@RequiredArgsConstructor
@Component
public class ClaimResolver implements HandlerMethodArgumentResolver {
    private final JwtService jwtService;
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(Claim.class) && methodParameter.getParameterType().equals(Claims.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String token = webRequest.getHeader("token");
        if(StringUtils.isBlank(token)){
            throw new ClaimException();
        }

        return jwtService.parseToken(token);
    }
}
