package at.procon.eventhub.processing.service;

import at.procon.eventhub.dto.DriverRefDto;
import at.procon.eventhub.dto.EventHubEventDto;
import at.procon.eventhub.processing.model.UnifiedRuntimeEventBundle;
import at.procon.eventhub.processing.model.UnifiedRuntimeProcessingRequest;
import at.procon.eventhub.tachographfilesession.model.ResolvedDriverTimeline;
import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class UnifiedRuntimeDriverTimelineService {

    private final UnifiedRuntimeEventAssemblyService runtimeEventAssemblyService;
    private final UnifiedEventTimelineReconstructor timelineReconstructor;

    public UnifiedRuntimeDriverTimelineService(
            UnifiedRuntimeEventAssemblyService runtimeEventAssemblyService,
            UnifiedEventTimelineReconstructor timelineReconstructor
    ) {
        this.runtimeEventAssemblyService = runtimeEventAssemblyService;
        this.timelineReconstructor = timelineReconstructor;
    }

    public ResolvedDriverTimeline loadDriverTimeline(UnifiedRuntimeProcessingRequest request) {
        UnifiedRuntimeEventBundle bundle = runtimeEventAssemblyService.assembleDriverScopedEvents(request);
        return timelineReconstructor.reconstruct(
                null,
                resolveDriverKey(request, bundle.mergedEvents()),
                bundle.mergedEvents()
        );
    }

    private String resolveDriverKey(
            UnifiedRuntimeProcessingRequest request,
            List<EventHubEventDto> events
    ) {
        if (request.driverKey() != null) {
            return request.driverKey();
        }
        if (request.driverSourceEntityId() != null) {
            return request.driverSourceEntityId();
        }
        for (EventHubEventDto event : events) {
            DriverRefDto driverRef = event.driverRef();
            if (driverRef != null && driverRef.hasAnyReference()) {
                return driverRef.stableKey();
            }
        }
        if (request.driverCardNation() != null && request.driverCardNumber() != null) {
            return request.driverCardNation() + ":" + request.driverCardNumber();
        }
        return request.driverCardNumber();
    }
}
