/*
 * File: src/main/java/reports/utility/JwtRequestUtils.java
 * Description: This utility class provides methods to extract information
 * from JWT (JSON Web Token) requests, specifically extracting tenant names
 * from HTTP headers. It utilizes a JwtUtils class for JWT operations.
*/

package com.nebula.erp.reports.utility;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

@Component
public class JwtRequestUtils {

    private final JwtUtils jwtUtils;
    private final HttpServletRequest httpServletRequest;

    // Constructor injection for JwtUtils
    public JwtRequestUtils(JwtUtils jwtUtils, HttpServletRequest httpServletRequest) {
        this.jwtUtils = jwtUtils;
        this.httpServletRequest = httpServletRequest;
    }

    // Method to extract token and tenant name
    public String getTenantNameFromHeaders(HttpHeaders headers) {
        // 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 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 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;
    }
}
