package com.unicorn.hgzero.stt.event.publisher;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * Azure Event Hub 이벤트 발행자 구현체
 * Azure Event Hubs를 통한 이벤트 발행 기능
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class EventHubPublisher implements EventPublisher {
    
    private final ObjectMapper objectMapper;
    
    @Override
    public void publish(String topic, Object event) {
        try {
            String eventData = objectMapper.writeValueAsString(event);
            
            // 실제로는 Azure Event Hubs SDK 사용
            // EventHubProducerClient producer = createProducer(topic);
            // EventDataBatch batch = producer.createBatch();
            // batch.tryAdd(new EventData(eventData));
            // producer.send(batch);
            
            // 시뮬레이션
            simulateEventHubPublish(topic, eventData);
            
            log.info("이벤트 발행 완료 - topic: {}, event: {}", topic, event.getClass().getSimpleName());
            
        } catch (Exception e) {
            log.error("이벤트 발행 실패 - topic: {}, event: {}", topic, event.getClass().getSimpleName(), e);
            throw new RuntimeException("이벤트 발행에 실패했습니다", e);
        }
    }
    
    @Override
    public void publishAsync(String topic, Object event) {
        CompletableFuture.runAsync(() -> {
            try {
                publish(topic, event);
            } catch (Exception e) {
                log.error("비동기 이벤트 발행 실패 - topic: {}, event: {}", topic, event.getClass().getSimpleName(), e);
            }
        });
    }
    
    /**
     * Azure Event Hub 발행 시뮬레이션
     */
    private void simulateEventHubPublish(String topic, String eventData) {
        log.debug("Event Hub 발행 시뮬레이션:");
        log.debug("Topic: {}", topic);
        log.debug("Event Data: {}", eventData);
        
        // 실제로는 다음과 같은 Azure Event Hubs 코드 사용:
        /*
        EventHubProducerClient producer = new EventHubClientBuilder()
            .connectionString(connectionString, eventHubName)
            .buildProducerClient();
            
        EventDataBatch batch = producer.createBatch();
        batch.tryAdd(new EventData(eventData));
        producer.send(batch);
        producer.close();
        */
    }
}