package com.zioinfo.cms.analytics;

import com.zioinfo.cms.analytics.mapper.AnalyticsMapper;
import com.zioinfo.cms.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 콘텐츠 성과 분석 API — 조회/체류/전환 집계 + BI 피드.
 *
 * <p>이벤트 기록(POST /event)은 공개 delivery 측에서 호출 가능하도록 작성 권한으로 보호된다.
 * BI(8006)가 /bi-feed 를 소비해 콘텐츠 전환 분석에 활용한다.
 */
@RestController
@RequestMapping("/api/cms/analytics")
@RequiredArgsConstructor
public class AnalyticsController {

    private final AnalyticsMapper mapper;

    /** 이벤트 기록 (VIEW/DWELL/CONVERSION). */
    @PostMapping("/event")
    public ApiResponse<Void> event(@RequestBody Map<String, Object> req) {
        Long contentId = longOf(req.get("contentId"));
        String type = req.get("eventType") == null ? "VIEW" : String.valueOf(req.get("eventType"));
        long amount = longOf(req.getOrDefault("amount", 1L)) == null ? 1L : longOf(req.get("amount"));
        if (contentId == null) throw new IllegalArgumentException("ERR-CMS-ANALYTICS-400: contentId 필수");
        mapper.recordEvent(contentId, type.toUpperCase(), amount);
        return ApiResponse.ok(null);
    }

    /** 인기 콘텐츠 Top N. */
    @GetMapping("/top")
    public ApiResponse<List<CmsContentStat>> top(@RequestParam(defaultValue = "10") int limit) {
        return ApiResponse.ok(mapper.topContent(limit));
    }

    /** 콘텐츠 단건 성과. */
    @GetMapping("/content/{id}")
    public ApiResponse<CmsContentStat> byContent(@PathVariable("id") Long contentId) {
        return ApiResponse.ok(mapper.findByContent(contentId));
    }

    /** 요약 통계. */
    @GetMapping("/summary")
    public ApiResponse<Map<String, Object>> summary() {
        Map<String, Object> m = new LinkedHashMap<>();
        long views = mapper.totalViews();
        long conv = mapper.totalConversions();
        m.put("totalViews", views);
        m.put("totalConversions", conv);
        m.put("conversionRate", views == 0 ? 0.0 : Math.round((double) conv / views * 10000) / 100.0);
        return ApiResponse.ok(m);
    }

    /** BI 피드 — 콘텐츠 성과를 BI(8006)가 소비. */
    @GetMapping("/bi-feed")
    public ApiResponse<Map<String, Object>> biFeed() {
        Map<String, Object> feed = new LinkedHashMap<>();
        feed.put("source", "GUARDiA CMS");
        feed.put("totalViews", mapper.totalViews());
        feed.put("totalConversions", mapper.totalConversions());
        feed.put("topContent", mapper.topContent(20));
        return ApiResponse.ok(feed);
    }

    private Long longOf(Object o) {
        if (o == null) return null;
        try { return Long.valueOf(String.valueOf(o).trim()); } catch (Exception e) { return null; }
    }
}
