package cn.lihongjie.coal.filter;

import cn.lihongjie.coal.common.Constants;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
*
*/
@Component
@Order(0)
@Slf4j
public class CacheFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        long start = System.currentTimeMillis();
        var req = new CacheBodyRequestWrapper(request);
        filterChain.doFilter(req, response);
        long end = System.currentTimeMillis();
        response.addHeader(Constants.HTTP_HEADER_RESPONSE_TIME, String.valueOf(end - start));

    }
}
