package com.lingniu.ingest.vehiclestat.jt808;

import com.lingniu.ingest.sink.kafka.proto.VehicleEnvelope;
import com.lingniu.ingest.vehiclestat.VehicleStatRepository;

import java.time.LocalDate;
import java.time.ZoneId;

public final class Jt808MileageStreamProcessor {

    private final Jt808LocationPointExtractor extractor;
    private final VehicleStatRepository repository;
    private final ZoneId zoneId;

    public Jt808MileageStreamProcessor(
            Jt808LocationPointExtractor extractor,
            VehicleStatRepository repository,
            ZoneId zoneId) {
        this.extractor = extractor;
        this.repository = repository;
        this.zoneId = zoneId;
    }

    public void process(VehicleEnvelope envelope) {
        extractor.extract(envelope).ifPresent(this::processPoint);
    }

    private void processPoint(Jt808LocationPoint point) {
        if (point.totalMileageKm() == null || !Double.isFinite(point.totalMileageKm())) {
            return;
        }
        LocalDate statDate = LocalDate.ofInstant(point.eventTime(), zoneId);
        repository.recordDailyMileageSample(statVehicleId(point), statDate, point.totalMileageKm());
    }

    private static String statVehicleId(Jt808LocationPoint point) {
        if (!point.vin().isBlank() && !"unknown".equalsIgnoreCase(point.vin())) {
            return point.vin();
        }
        return point.vehicleKey();
    }
}
