package com.lingniu.ingest.sink.kafka;

import com.lingniu.ingest.api.consumer.EnvelopeDeadLetterRecord;
import com.lingniu.ingest.api.consumer.EnvelopeDeadLetterSink;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.nio.charset.StandardCharsets;

public final class KafkaEnvelopeDeadLetterSink implements EnvelopeDeadLetterSink {

    private final Producer<String, byte[]> producer;
    private final String topic;

    public KafkaEnvelopeDeadLetterSink(KafkaProducer<String, byte[]> producer, String topic) {
        this((Producer<String, byte[]>) producer, topic);
    }

    KafkaEnvelopeDeadLetterSink(Producer<String, byte[]> producer, String topic) {
        if (producer == null) {
            throw new IllegalArgumentException("producer must not be null");
        }
        if (topic == null || topic.isBlank()) {
            throw new IllegalArgumentException("topic must not be blank");
        }
        this.producer = producer;
        this.topic = topic;
    }

    @Override
    public void publish(EnvelopeDeadLetterRecord record) {
        if (record == null) {
            throw new IllegalArgumentException("record must not be null");
        }
        ProducerRecord<String, byte[]> out = new ProducerRecord<>(topic, record.key(), record.payload());
        // DLQ payload 保持原始 Kafka value；定位信息全部放 header，便于后续重放或人工排查。
        header(out, "dlq-service", record.service());
        header(out, "dlq-source-topic", record.topic());
        header(out, "dlq-source-partition", Integer.toString(record.partition()));
        header(out, "dlq-source-offset", Long.toString(record.offset()));
        header(out, "dlq-status", record.status().name());
        header(out, "dlq-event-id", record.eventId());
        header(out, "dlq-vin", record.vin());
        header(out, "dlq-message", record.message());
        header(out, "dlq-created-at", record.createdAt().toString());
        producer.send(out);
    }

    private static void header(ProducerRecord<String, byte[]> record, String key, String value) {
        record.headers().add(key, value.getBytes(StandardCharsets.UTF_8));
    }
}
