package com.nebula.erp.inventory.utility;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

@Component
public class JwtRequestUtils {

    private final JwtUtils jwtUtils;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Value("${allowed.ips}")
    private String allowedIps;

    public JwtRequestUtils(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    // Check if the current request IP is allowed
    private boolean isRequestFromAllowedIp() {
        String clientIp = httpServletRequest.getRemoteAddr();

        // Split the allowed IPs into an array
        String[] allowedIpArray = allowedIps.split(",");

        // Extract the Authorization header
        String authorizationHeader = httpServletRequest.getHeader("Authorization");
        for (String allowedIp : allowedIpArray) {
            if (clientIp.equals(allowedIp) && (authorizationHeader == null || authorizationHeader.isEmpty())) {
                return true;
            }
        }
        return false;
    }

    // Method to get Authorization Headers
    public HttpHeaders getAuthorizationHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION));
        return headers;
    }

    // Method to extract token and tenant name
    public String getTenantName() {
        if (isRequestFromAllowedIp()) {
            return "ALL"; // Return a default tenant for allowed IPs
        }
        HttpHeaders headers = getAuthorizationHeaders();
        // Extract the JWT token from the Authorization header
        String token = jwtUtils.extractTokenFromHeaders(headers);

        // Get the tenant name using the token
        String tenantName = jwtUtils.getTenantName(token);
        if (tenantName == null || tenantName.isEmpty()) {
            throw new RuntimeException("Tenant name is missing in the token.");
        }

        return tenantName;
    }

    // Method to extract token and user id
    public String getUserId() {
        HttpHeaders headers = getAuthorizationHeaders();
        // Extract the JWT token from the Authorization header
        String token = jwtUtils.extractTokenFromHeaders(headers);

        // Get the user id using the token
        String userId = jwtUtils.getUserId(token);
        if (userId == null || userId.isEmpty()) {
            throw new RuntimeException("User ID is missing in the token.");
        }

        return userId;
    }
}