package com.lingniu.ingest.api.event;

import com.lingniu.ingest.api.ProtocolId;
import org.junit.jupiter.api.Test;

import java.time.Instant;
import java.util.List;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class TelemetrySnapshotTest {

    @Test
    void indexesFieldsByInternalKey() {
        TelemetrySnapshot snapshot = new TelemetrySnapshot(
                "event-1",
                "VIN001",
                ProtocolId.GB32960,
                "REALTIME",
                Instant.parse("2026-06-22T08:00:00Z"),
                Instant.parse("2026-06-22T08:00:01Z"),
                "archive://raw/event-1.bin",
                Map.of("protocolVersion", "V2016"),
                List.of(
                        TelemetryFieldValue.doubleValue("total_mileage_km", 120.5, "km", "gb32960.vehicle.totalMileageKm"),
                        TelemetryFieldValue.booleanValue("hydrogen_leak_detected", true, "", "gb32960.alarm.HYDROGEN_LEAK")
                )
        );

        assertThat(snapshot.field("total_mileage_km")).isPresent();
        assertThat(snapshot.field("total_mileage_km").orElseThrow().value()).isEqualTo("120.5");
        assertThat(snapshot.field("hydrogen_leak_detected").orElseThrow().value()).isEqualTo("true");
        assertThat(snapshot.field("unknown")).isEmpty();
        assertThat(snapshot.metadata()).containsEntry("protocolVersion", "V2016");
    }

    @Test
    void rejectsDuplicateFieldKeys() {
        assertThatThrownBy(() -> new TelemetrySnapshot(
                "event-1",
                "VIN001",
                ProtocolId.GB32960,
                "REALTIME",
                Instant.parse("2026-06-22T08:00:00Z"),
                Instant.parse("2026-06-22T08:00:01Z"),
                "",
                Map.of(),
                List.of(
                        TelemetryFieldValue.doubleValue("speed_kmh", 1.0, "km/h", "a"),
                        TelemetryFieldValue.doubleValue("speed_kmh", 2.0, "km/h", "b")
                )
        ))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining("duplicate");
    }
}
