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

import at.procon.eventhub.dto.DriverRefDto;
import at.procon.eventhub.dto.EventHubEventDto;
import at.procon.eventhub.dto.VehicleRefDto;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.stereotype.Component;

@Component
public class RuntimeEventScopeClassifier {

    public RuntimeEventScopeType classify(EventHubEventDto event) {
        if (event == null) {
            return RuntimeEventScopeType.UNKNOWN;
        }
        boolean hasDriver = hasDriver(event);
        boolean hasVehicle = hasVehicle(event);
        if (hasDriver && hasVehicle) {
            return RuntimeEventScopeType.DRIVER_VEHICLE_SCOPED;
        }
        if (hasDriver) {
            return RuntimeEventScopeType.DRIVER_SCOPED;
        }
        if (hasVehicle) {
            return RuntimeEventScopeType.VEHICLE_SCOPED;
        }
        return RuntimeEventScopeType.GLOBAL_SUPPORT;
    }

    public boolean hasDriver(EventHubEventDto event) {
        if (event == null) {
            return false;
        }
        if (text(rawPayload(event), "driverKey") != null) {
            return true;
        }
        DriverRefDto driverRef = event.driverRef();
        return driverRef != null && driverRef.hasAnyReference();
    }

    public boolean hasVehicle(EventHubEventDto event) {
        if (event == null) {
            return false;
        }
        JsonNode raw = rawPayload(event);
        if (text(raw, "vehicleKey") != null || text(raw, "registrationKey") != null) {
            return true;
        }
        VehicleRefDto vehicleRef = event.vehicleRef();
        return vehicleRef != null && vehicleRef.hasAnyReference();
    }

    private JsonNode rawPayload(EventHubEventDto event) {
        JsonNode payload = event.payload();
        if (payload == null || payload.isNull()) {
            return null;
        }
        JsonNode raw = payload.get("raw");
        return raw == null || raw.isNull() ? payload : raw;
    }

    private String text(JsonNode node, String field) {
        if (node == null || field == null) {
            return null;
        }
        JsonNode value = node.get(field);
        if (value == null || value.isNull()) {
            return null;
        }
        String text = value.asText(null);
        return text == null || text.isBlank() ? null : text.trim();
    }
}
