package infrastructure.filter;

import com.banesco.common.infraestructure.helpers.RequestHelper;
import infrastructure.context.TraceIdContext;
import jakarta.annotation.Priority;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.ext.Provider;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Provider
@Priority(100)
public class TraceIdFilter implements ContainerRequestFilter {

    @Inject
    TraceIdContext traceIdContext;

    @Override
    public void filter(ContainerRequestContext requestContext) {
        var headerId = requestContext.getHeaderString("requestId");
        var finalTraceId = (headerId != null && !headerId.isBlank()) ? headerId : RequestHelper.randomAlphanumeric(20);
        traceIdContext.setTraceId(finalTraceId);
    }
}