package com.gnx.telemedicine.config;

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 add API version information to response headers.
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ApiVersionInterceptor implements HandlerInterceptor {
    
    private final ApiVersionConfig apiVersionConfig;
    
    private static final String API_VERSION_HEADER = "API-Version";
    private static final String API_DEPRECATED_HEADER = "API-Deprecated";
    private static final String API_SUNSET_HEADER = "API-Sunset";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!apiVersionConfig.isVersioningEnabled()) {
            return true;
        }
        
        // Extract API version from request path
        String requestPath = request.getRequestURI();
        String apiVersion = extractApiVersion(requestPath);
        
        if (apiVersion != null) {
            // Add version to response headers
            if (apiVersionConfig.isShowVersionInHeaders()) {
                response.setHeader(API_VERSION_HEADER, apiVersion);
            }
            
            // Check if version is deprecated
            if (isDeprecated(apiVersion)) {
                if (apiVersionConfig.isShowDeprecationWarnings()) {
                    response.setHeader(API_DEPRECATED_HEADER, "true");
                    response.setHeader(API_SUNSET_HEADER, getSunsetDate(apiVersion));
                    log.warn("Deprecated API version {} used for path: {}", apiVersion, requestPath);
                }
            }
        }
        
        return true;
    }
    
    /**
     * Extract API version from request path.
     * @param requestPath Request path (e.g., "/api/v3/auth/login")
     * @return API version (e.g., "v1") or null if not found
     */
    private String extractApiVersion(String requestPath) {
        if (requestPath == null || requestPath.isEmpty()) {
            return null;
        }
        
        // Check for /api/vX pattern
        String[] parts = requestPath.split("/");
        for (int i = 0; i < parts.length - 1; i++) {
            if ("api".equals(parts[i]) && i + 1 < parts.length) {
                String version = parts[i + 1];
                if (version.startsWith("v") && version.length() > 1) {
                    return version;
                }
            }
        }
        
        return null;
    }
    
    /**
     * Check if an API version is deprecated.
     * @param version API version to check
     * @return true if version is deprecated
     */
    private boolean isDeprecated(String version) {
        // For now, only current version is not deprecated
        // In the future, you can add deprecation logic here
        return false; // TODO: Implement deprecation logic
    }
    
    /**
     * Get sunset date for a deprecated API version.
     * @param version API version
     * @return Sunset date in RFC 1123 format
     */
    private String getSunsetDate(String version) {
        // For now, return a default sunset date
        // In the future, you can configure this per version
        return "Sun, 01 Jan 2025 00:00:00 GMT"; // TODO: Configure per version
    }
}

