package com.nebula.erp.sales.utility;

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

@Component
public class JwtRequestUtils {

    private final JwtUtils jwtUtils;

    @Autowired
    private HttpServletRequest httpServletRequest;

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

    // 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() {
        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;
    }
}