package at.procon.eventhub.processing.driverworkingtime.model;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public record DriverWorkingTimeVehicleUsageInterval(
        UUID sessionId,
        String driverKey,
        String intervalId,
        String firstSourceIntervalId,
        String lastSourceIntervalId,
        OffsetDateTime startedAt,
        OffsetDateTime endedAt,
        long startedAtEpochSecond,
        Long endedAtEpochSecond,
        long durationSeconds,
        Long odometerBeginKm,
        Long odometerEndKm,
        String registrationKey,
        String vehicleKey,
        String sourceKind,
        List<String> sourceIntervalIds
) {
    public DriverWorkingTimeVehicleUsageInterval {
        sourceIntervalIds = sourceIntervalIds == null ? List.of() : List.copyOf(sourceIntervalIds);
    }

    public static DriverWorkingTimeVehicleUsageInterval fromMap(Map<String, Object> values) {
        if (values == null) {
            return null;
        }
        return new DriverWorkingTimeVehicleUsageInterval(
                (UUID) values.get("sessionId"),
                (String) values.get("driverKey"),
                (String) values.get("intervalId"),
                (String) values.get("firstSourceIntervalId"),
                (String) values.get("lastSourceIntervalId"),
                (OffsetDateTime) values.get("startedAt"),
                (OffsetDateTime) values.get("endedAt"),
                asLong(values.get("startedAtEpochSecond")),
                asNullableLong(values.get("endedAtEpochSecond")),
                asLong(values.get("durationSeconds")),
                asNullableLong(values.get("odometerBeginKm")),
                asNullableLong(values.get("odometerEndKm")),
                (String) values.get("registrationKey"),
                (String) values.get("vehicleKey"),
                (String) values.get("sourceKind"),
                castStringList(values.get("sourceIntervalIds"))
        );
    }

    @SuppressWarnings("unchecked")
    private static List<String> castStringList(Object value) {
        return value instanceof List<?> list ? (List<String>) list : List.of();
    }

    private static long asLong(Object value) {
        return value instanceof Number number ? number.longValue() : 0L;
    }

    private static Long asNullableLong(Object value) {
        return value instanceof Number number ? number.longValue() : null;
    }
}
