package com.lingniu.ingest.vehiclestate;

import com.google.protobuf.InvalidProtocolBufferException;
import com.lingniu.ingest.api.consumer.EnvelopeIngestResult;
import com.lingniu.ingest.api.consumer.EnvelopeIngestor;
import com.lingniu.ingest.sink.kafka.proto.VehicleEnvelope;

public final class VehicleStateEnvelopeIngestor implements EnvelopeIngestor {

    private final VehicleStateUpdater updater;

    public VehicleStateEnvelopeIngestor(VehicleStateUpdater updater) {
        if (updater == null) {
            throw new IllegalArgumentException("updater must not be null");
        }
        this.updater = updater;
    }

    public void ingest(byte[] kafkaValue) {
        VehicleEnvelope envelope = parse(kafkaValue);
        if (!envelope.hasTelemetrySnapshot()) {
            return;
        }
        updater.update(envelope);
    }

    @Override
    public EnvelopeIngestResult tryIngest(byte[] kafkaValue) {
        VehicleEnvelope envelope = null;
        try {
            envelope = parse(kafkaValue);
            if (!envelope.hasTelemetrySnapshot()) {
                return EnvelopeIngestResult.skipped(
                        envelope.getEventId(), envelope.getVin(), "envelope telemetry_snapshot is required");
            }
            // Kafka 消费路径只接受标准 VehicleEnvelope；坏消息返回明确结果给处理器写 DLQ。
            updater.update(envelope);
            return EnvelopeIngestResult.processed(envelope.getEventId(), envelope.getVin());
        } catch (IllegalArgumentException ex) {
            return envelope == null
                    ? EnvelopeIngestResult.invalid(ex.getMessage())
                    : EnvelopeIngestResult.skipped(envelope.getEventId(), envelope.getVin(), ex.getMessage());
        }
    }

    private static VehicleEnvelope parse(byte[] kafkaValue) {
        if (kafkaValue == null || kafkaValue.length == 0) {
            throw new IllegalArgumentException("VehicleEnvelope bytes must not be empty");
        }
        try {
            return VehicleEnvelope.parseFrom(kafkaValue);
        } catch (InvalidProtocolBufferException ex) {
            throw new IllegalArgumentException("VehicleEnvelope bytes are invalid", ex);
        }
    }
}
