package com.smyhub.store.mengyastorebackendjava.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smyhub.store.mengyastorebackendjava.dto.response.ApiResponse;
import com.smyhub.store.mengyastorebackendjava.service.SproutGateAuthService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
public class BearerTokenInterceptor implements HandlerInterceptor {

    private final SproutGateAuthService authService;
    private final ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("Authorization");
        if (!StringUtils.hasText(header) || !header.startsWith("Bearer ")) {
            return sendUnauthorized(response, "请先登录");
        }
        String token = header.substring(7);
        SproutGateVerifyResult result = authService.verifyToken(token);
        if (!result.isValid() || result.getUser() == null) {
            return sendUnauthorized(response, "登录已过期，请重新登录");
        }
        CurrentUserHolder.set(result.getUser());
        return true;
    }

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

    private boolean sendUnauthorized(HttpServletResponse response, String message) throws Exception {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        objectMapper.writeValue(response.getWriter(), ApiResponse.error(message));
        return false;
    }
}
