package com.unicorn.hgzero.notification.config;

import com.azure.messaging.eventhubs.EventProcessorClient;
import com.azure.messaging.eventhubs.EventProcessorClientBuilder;
import com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore;
import com.azure.messaging.eventhubs.models.EventContext;
import com.azure.storage.blob.BlobContainerAsyncClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.function.Consumer;

/**
 * Azure Event Hubs 설정
 *
 * EventProcessorClient 구성 및 이벤트 처리 설정
 * Blob Storage 기반 Checkpoint 관리
 *
 * @author 준호 (Backend Developer)
 * @version 1.0
 * @since 2025-10-23
 */
@Slf4j
@Configuration
public class EventHubConfig {

    @Value("${azure.eventhub.connection-string}")
    private String eventHubConnectionString;

    @Value("${azure.eventhub.name}")
    private String eventHubName;

    @Value("${azure.eventhub.consumer-group}")
    private String consumerGroup;

    /**
     * EventProcessorClient Bean 생성
     *
     * @param blobContainerAsyncClient Blob Storage 클라이언트
     * @param eventHandler 이벤트 핸들러
     * @return EventProcessorClient
     */
    @Bean
    public EventProcessorClient eventProcessorClient(
        BlobContainerAsyncClient blobContainerAsyncClient,
        Consumer<EventContext> eventHandler
    ) {
        log.info("EventProcessorClient 생성 중 - EventHub: {}, ConsumerGroup: {}",
            eventHubName, consumerGroup);

        // Blob Checkpoint Store 생성
        BlobCheckpointStore checkpointStore = new BlobCheckpointStore(blobContainerAsyncClient);

        // EventProcessorClient 빌더 구성
        EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder()
            .connectionString(eventHubConnectionString, eventHubName)
            .consumerGroup(consumerGroup)
            .checkpointStore(checkpointStore)
            .processEvent(eventHandler)
            .processError(errorContext -> {
                log.error("이벤트 처리 오류 발생 - PartitionId: {}, ErrorType: {}",
                    errorContext.getPartitionContext().getPartitionId(),
                    errorContext.getThrowable().getClass().getSimpleName(),
                    errorContext.getThrowable());
            })
            .buildEventProcessorClient();

        log.info("EventProcessorClient 생성 완료");

        return eventProcessorClient;
    }
}
