package com.gnx.telemedicine.metrics;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Interceptor to record API metrics for all requests.
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class MetricsInterceptor implements HandlerInterceptor {
    
    private final TelemedicineMetrics telemedicineMetrics;
    private final MeterRegistry meterRegistry;
    private static final String START_TIME_ATTRIBUTE = "metrics.startTime";
    private static final String TIMER_SAMPLE_ATTRIBUTE = "metrics.timerSample";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // Record start time
        request.setAttribute(START_TIME_ATTRIBUTE, System.currentTimeMillis());
        
        // Start timer
        Timer.Sample sample = Timer.start(meterRegistry);
        request.setAttribute(TIMER_SAMPLE_ATTRIBUTE, sample);
        
        // Record API request
        String endpoint = request.getRequestURI();
        String method = request.getMethod();
        telemedicineMetrics.recordApiRequest(endpoint, method);
        
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // Record response time
        Timer.Sample sample = (Timer.Sample) request.getAttribute(TIMER_SAMPLE_ATTRIBUTE);
        if (sample != null) {
            String endpoint = request.getRequestURI();
            String method = request.getMethod();
            
            // Record response time
            telemedicineMetrics.recordApiResponseTime(sample, endpoint, method);
            
            // Record errors
            if (ex != null || response.getStatus() >= 400) {
                String status = String.valueOf(response.getStatus());
                telemedicineMetrics.recordApiError(endpoint, method, status);
            }
        }
    }
}

