package com.kt.event.analytics.controller;

import com.kt.event.analytics.dto.response.UserChannelAnalyticsResponse;
import com.kt.event.analytics.service.UserChannelAnalyticsService;
import com.kt.event.common.dto.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * User Channel Analytics Controller
 */
@Tag(name = "User Channels", description = "사용자 전체 이벤트 채널별 성과 분석 API")
@Slf4j
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserChannelAnalyticsController {

    private final UserChannelAnalyticsService userChannelAnalyticsService;

    @Operation(
        summary = "사용자 전체 채널별 성과 분석",
        description = "사용자의 모든 이벤트 채널 성과를 통합하여 분석합니다."
    )
    @GetMapping("/{userId}/analytics/channels")
    public ResponseEntity<ApiResponse<UserChannelAnalyticsResponse>> getUserChannelAnalytics(
        @Parameter(description = "사용자 ID", required = true)
        @PathVariable String userId,

        @Parameter(description = "조회할 채널 목록 (쉼표로 구분)")
        @RequestParam(required = false)
        String channels,

        @Parameter(description = "정렬 기준")
        @RequestParam(required = false, defaultValue = "participants")
        String sortBy,

        @Parameter(description = "정렬 순서")
        @RequestParam(required = false, defaultValue = "desc")
        String order,

        @Parameter(description = "조회 시작 날짜")
        @RequestParam(required = false)
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
        LocalDateTime startDate,

        @Parameter(description = "조회 종료 날짜")
        @RequestParam(required = false)
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
        LocalDateTime endDate,

        @Parameter(description = "캐시 갱신 여부")
        @RequestParam(required = false, defaultValue = "false")
        Boolean refresh
    ) {
        log.info("사용자 채널 분석 API 호출: userId={}, sortBy={}", userId, sortBy);

        List<String> channelList = channels != null && !channels.isBlank()
            ? Arrays.asList(channels.split(","))
            : null;

        UserChannelAnalyticsResponse response = userChannelAnalyticsService.getUserChannelAnalytics(
            userId, channelList, sortBy, order, startDate, endDate, refresh
        );

        return ResponseEntity.ok(ApiResponse.success(response));
    }
}
