package at.procon.eventhub.processing.eventprocessing.plan;

import at.procon.eventhub.processing.dto.UnifiedRuntimeProcessingApiRequest;
import at.procon.eventhub.processing.eventprocessing.dto.RuntimeEventPartitioningApiRequest;
import com.fasterxml.jackson.annotation.JsonAlias;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public record RuntimeProcessingExecutionApiRequest(
        String processingPlanKey,
        @JsonAlias("scope") UnifiedRuntimeProcessingApiRequest sourceSelection,
        RuntimeEventPartitioningApiRequest partitioning,
        List<String> modules,
        Map<String, Object> parameters
) {
    public RuntimeProcessingExecutionApiRequest {
        if (processingPlanKey == null || processingPlanKey.isBlank()) {
            throw new IllegalArgumentException("processingPlanKey must not be blank");
        }
        processingPlanKey = processingPlanKey.trim();
        if (sourceSelection == null) {
            throw new IllegalArgumentException("sourceSelection must not be null");
        }
        partitioning = partitioning == null
                ? new RuntimeEventPartitioningApiRequest(null, null, null, null, null, null, null, null, null, null)
                : partitioning;
        modules = modules == null ? List.of() : List.copyOf(modules);
        parameters = parameters == null
                ? Map.of()
                : Collections.unmodifiableMap(new LinkedHashMap<>(parameters));
    }

    public UnifiedRuntimeProcessingApiRequest scope() {
        return sourceSelection;
    }

    public static RuntimeProcessingExecutionApiRequest driverWorkingTime(UnifiedRuntimeProcessingApiRequest sourceSelection) {
        return new RuntimeProcessingExecutionApiRequest(
                DriverWorkingTimeRuntimeProcessingPlan.PLAN_KEY,
                sourceSelection,
                new RuntimeEventPartitioningApiRequest(
                        at.procon.eventhub.processing.eventprocessing.partition.RuntimeEventPartitioningStrategy.DRIVER,
                        null,
                        sourceSelection != null ? sourceSelection.includeAllDrivers() : null,
                        sourceSelection != null ? sourceSelection.driverKeys() : null,
                        sourceSelection != null ? sourceSelection.includeAllDrivers() : null,
                        sourceSelection != null ? sourceSelection.vehicleKeys() : null,
                        sourceSelection != null ? sourceSelection.includeAllVehicles() : null,
                        null,
                        sourceSelection != null ? sourceSelection.vehicleExpansionPaddingMinutes() : null,
                        null
                ),
                List.of(),
                Map.of()
        );
    }
}
