package com.kt.distribution.service;

import com.kt.distribution.event.DistributionCompletedEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * Kafka Event Publisher
 * DistributionCompleted 이벤트를 Kafka로 발행
 *
 * @author System Architect
 * @since 2025-10-23
 */
@Slf4j
@Service
@ConditionalOnProperty(name = "spring.kafka.enabled", havingValue = "true", matchIfMissing = true)
@RequiredArgsConstructor
public class KafkaEventPublisher {

    private final KafkaTemplate<String, Object> kafkaTemplate;

    @Value("${kafka.topics.distribution-completed}")
    private static String distributionCompletedTopic = "distribution-completed";

    /**
     * 배포 완료 이벤트 발행
     *
     * @param event DistributionCompletedEvent
     */
    public void publishDistributionCompleted(DistributionCompletedEvent event) {
        try {
            log.info("Publishing DistributionCompletedEvent: eventId={}, channels={}",
                    event.getEventId(), event.getDistributedChannels().size());

            CompletableFuture<SendResult<String, Object>> future =
                    kafkaTemplate.send(distributionCompletedTopic, event.getEventId(), event);

            future.whenComplete((result, ex) -> {
                if (ex == null) {
                    log.info("DistributionCompletedEvent published successfully: topic={}, partition={}, offset={}",
                            distributionCompletedTopic,
                            result.getRecordMetadata().partition(),
                            result.getRecordMetadata().offset());
                } else {
                    log.error("Failed to publish DistributionCompletedEvent: eventId={}, error={}",
                            event.getEventId(), ex.getMessage(), ex);
                }
            });

        } catch (Exception e) {
            log.error("Error publishing DistributionCompletedEvent: eventId={}, error={}",
                    event.getEventId(), e.getMessage(), e);
        }
    }
}
