package com.kt.event.analytics.service;

import com.kt.event.analytics.dto.response.RoiAnalyticsResponse;
import com.kt.event.analytics.entity.ChannelStats;
import com.kt.event.analytics.entity.EventStats;
import com.kt.event.analytics.repository.ChannelStatsRepository;
import com.kt.event.analytics.repository.EventStatsRepository;
import com.kt.event.common.exception.BusinessException;
import com.kt.event.common.exception.ErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ROI 분석 Service
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class RoiAnalyticsService {

    private final EventStatsRepository eventStatsRepository;
    private final ChannelStatsRepository channelStatsRepository;
    private final ROICalculator roiCalculator;

    /**
     * ROI 상세 분석 조회
     */
    public RoiAnalyticsResponse getRoiAnalytics(String eventId, boolean includeProjection) {
        log.info("ROI 상세 분석 조회: eventId={}, includeProjection={}", eventId, includeProjection);

        // 이벤트 통계 조회
        EventStats eventStats = eventStatsRepository.findByEventId(eventId)
            .orElseThrow(() -> new BusinessException(ErrorCode.EVENT_001));

        // 채널별 통계 조회
        List<ChannelStats> channelStatsList = channelStatsRepository.findByEventId(eventId);

        // ROI 상세 계산
        RoiAnalyticsResponse response = roiCalculator.calculateDetailedRoi(eventStats, channelStatsList);

        // 예측 데이터 제외 옵션
        if (!includeProjection) {
            response.setProjection(null);
        }

        return response;
    }
}
