package com.maternalmall.config;

import com.maternalmall.domain.User;
import com.maternalmall.repository.UserRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    private final UserRepository userRepository;

    @Value("${app.token-header:X-Token}")
    private String tokenHeader;

    private static final java.util.List<String> PUBLIC_PATHS = java.util.Arrays.asList(
            "/api/auth/login",
            "/api/auth/register",
            "/api/public"
    );

    public AuthInterceptor(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Let browser CORS preflight pass without auth token.
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String path = contextPath.isEmpty() ? uri : uri.substring(contextPath.length());
        
        if (uri.equals("/") || uri.startsWith("/error") || 
            PUBLIC_PATHS.stream().anyMatch(p -> path.equals(p) || path.startsWith(p + "/") || path.startsWith(p + "?"))) {
            return true;
        }
        String token = request.getHeader(tokenHeader);
        if (token == null || token.isBlank()) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            response.getWriter().write("{\"code\":401,\"message\":\"请先登录\",\"data\":null}");
            return false;
        }
        User user = userRepository.findByToken(token).orElse(null);
        if (user == null || !Boolean.TRUE.equals(user.getEnabled())) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            response.getWriter().write("{\"code\":401,\"message\":\"登录状态无效\",\"data\":null}");
            return false;
        }
        request.setAttribute(AuthContext.CURRENT_USER, user);
        return true;
    }
}
