package dev.lions.user.manager.client.filter;

import io.quarkus.oidc.AccessTokenCredential;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import org.eclipse.microprofile.rest.client.ext.ClientHeadersFactory;

import java.util.logging.Logger;

/**
 * Factory to automatically add the OIDC access token (Bearer)
 * to REST Client request headers.
 */
@RequestScoped
public class AuthHeaderFactory implements ClientHeadersFactory {

    private static final Logger LOGGER = Logger.getLogger(AuthHeaderFactory.class.getName());

    @Inject
    AccessTokenCredential accessTokenCredential;

    @Override
    public MultivaluedMap<String, String> update(
            MultivaluedMap<String, String> incomingHeaders,
            MultivaluedMap<String, String> clientOutgoingHeaders) {

        MultivaluedMap<String, String> result = new MultivaluedHashMap<>();

        // 1. Log incoming and outgoing headers for debugging
        if (incomingHeaders != null) {
            LOGGER.fine("Incoming Headers: " + incomingHeaders.keySet());
        }
        if (clientOutgoingHeaders != null) {
            LOGGER.fine("Client Outgoing Headers: " + clientOutgoingHeaders.keySet());
        }

        try {
            if (accessTokenCredential != null) {
                // 2. Check if the token is available
                String accessToken = accessTokenCredential.getToken();
                if (accessToken != null && !accessToken.isEmpty()) {
                    result.add("Authorization", "Bearer " + accessToken);
                    LOGGER.info("Access token added to Authorization header. Token length: " + accessToken.length());
                } else {
                    LOGGER.warning("Access token is empty or null in AccessTokenCredential.");
                }
            } else {
                LOGGER.warning("AccessTokenCredential is unavailable - user might not be authenticated.");
            }
        } catch (Exception e) {
            LOGGER.severe("Error adding Bearer token: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }
}
