package com.kt.ai.test.integration.kafka;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.kt.ai.kafka.message.AIJobMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;

import java.time.LocalDateTime;
import java.util.Properties;
import java.util.concurrent.Future;

/**
 * Kafka 테스트용 Producer 유틸리티
 *
 * @author AI Service Team
 * @since 1.0.0
 */
@Slf4j
public class KafkaTestProducer {

    private final KafkaProducer<String, String> producer;
    private final ObjectMapper objectMapper;
    private final String topic;

    public KafkaTestProducer(String bootstrapServers, String topic) {
        this.topic = topic;
        this.objectMapper = new ObjectMapper();
        this.objectMapper.registerModule(new JavaTimeModule());

        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        props.put(ProducerConfig.RETRIES_CONFIG, 3);

        this.producer = new KafkaProducer<>(props);
    }

    /**
     * AI Job 메시지 전송
     */
    public RecordMetadata sendAIJobMessage(AIJobMessage message) {
        try {
            String json = objectMapper.writeValueAsString(message);
            ProducerRecord<String, String> record = new ProducerRecord<>(topic, message.getJobId(), json);

            Future<RecordMetadata> future = producer.send(record);
            RecordMetadata metadata = future.get();

            log.info("Kafka 메시지 전송 성공: topic={}, partition={}, offset={}, jobId={}",
                    metadata.topic(), metadata.partition(), metadata.offset(), message.getJobId());

            return metadata;
        } catch (Exception e) {
            log.error("Kafka 메시지 전송 실패: jobId={}", message.getJobId(), e);
            throw new RuntimeException("Kafka 메시지 전송 실패", e);
        }
    }

    /**
     * 테스트용 샘플 메시지 생성
     */
    public static AIJobMessage createSampleMessage(String jobId, String eventId) {
        return AIJobMessage.builder()
                .jobId(jobId)
                .eventId(eventId)
                .objective("신규 고객 유치")
                .industry("음식점")
                .region("강남구")
                .storeName("테스트 BBQ 레스토랑")
                .targetAudience("20-30대 직장인")
                .budget(500000)
                .requestedAt(LocalDateTime.now())
                .build();
    }

    /**
     * Producer 종료
     */
    public void close() {
        if (producer != null) {
            producer.close();
            log.info("Kafka Producer 종료");
        }
    }
}
