package com.mosquito.project.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mosquito.project.config.ApiVersion;
import com.mosquito.project.dto.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.time.OffsetDateTime;

@Component
public class ApiResponseWrapperInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(ApiResponseWrapperInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        if (response.getStatus() >= 200 && response.getStatus() < 300) {
            String requestedVersion = request.getHeader(ApiVersion.HEADER_NAME);
            if (requestedVersion == null || requestedVersion.isBlank()) {
                requestedVersion = ApiVersion.DEFAULT_VERSION;
            }
            response.setHeader(ApiVersion.HEADER_NAME, requestedVersion);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) {
        long duration = System.currentTimeMillis() - (Long) request.getAttribute("startTime");
        if (request.getRequestURI().startsWith("/api/")) {
            log.debug("API Request: {} {} - {}ms", request.getMethod(), request.getRequestURI(), duration);
        }
    }
}
