package com.smyhub.store.mengyastorebackendjava.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smyhub.store.mengyastorebackendjava.config.AppProperties;
import com.smyhub.store.mengyastorebackendjava.dto.response.ApiResponse;
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 AdminTokenInterceptor implements HandlerInterceptor {

    private final AppProperties appProperties;
    private final ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = resolveToken(request);
        if (StringUtils.hasText(token) && token.equals(appProperties.getAdminToken())) {
            return true;
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        objectMapper.writeValue(response.getWriter(), ApiResponse.error("unauthorized"));
        return false;
    }

    private String resolveToken(HttpServletRequest request) {
        String token = request.getHeader("X-Admin-Token");
        if (StringUtils.hasText(token)) {
            return token;
        }
        token = request.getHeader("Authorization");
        if (StringUtils.hasText(token)) {
            return token;
        }
        return request.getParameter("token");
    }
}
