package com.kt.ai.kafka.consumer;

import com.kt.ai.kafka.message.AIJobMessage;
import com.kt.ai.service.AIRecommendationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * AI Job Kafka Consumer
 * - Topic: ai-event-generation-job
 * - Consumer Group: ai-service-consumers
 *
 * @author AI Service Team
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AIJobConsumer {

    private final AIRecommendationService aiRecommendationService;

    /**
     * Kafka 메시지 수신 및 처리
     */
    @KafkaListener(
            topics = "${kafka.topics.ai-job}",
            groupId = "${spring.kafka.consumer.group-id}",
            containerFactory = "kafkaListenerContainerFactory"
    )
    public void consume(
            @Payload AIJobMessage message,
            @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
            @Header(KafkaHeaders.OFFSET) Long offset,
            Acknowledgment acknowledgment
    ) {
        try {
            log.info("Kafka 메시지 수신: topic={}, offset={}, jobId={}, eventId={}",
                    topic, offset, message.getJobId(), message.getEventId());

            // AI 추천 생성
            aiRecommendationService.generateRecommendations(message);

            // Manual ACK
            acknowledgment.acknowledge();
            log.info("Kafka 메시지 처리 완료: jobId={}", message.getJobId());

        } catch (Exception e) {
            log.error("Kafka 메시지 처리 실패: jobId={}", message.getJobId(), e);
            // DLQ로 이동하거나 재시도 로직 추가 가능
            acknowledgment.acknowledge();  // 실패한 메시지도 ACK (DLQ로 이동)
        }
    }
}
