package com.mosquito.project.controller;

import com.mosquito.project.dto.ShareMetricsResponse;
import com.mosquito.project.dto.ShareTrackingResponse;
import com.mosquito.project.dto.ApiResponse;
import com.mosquito.project.service.ShareConfigService;
import com.mosquito.project.service.ShareTrackingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/share")
@Tag(name = "Share Tracking", description = "分享链接跟踪与数据分析API")
public class ShareTrackingController {

    private static final Logger log = LoggerFactory.getLogger(ShareTrackingController.class);

    private final ShareTrackingService trackingService;
    private final ShareConfigService shareConfigService;

    public ShareTrackingController(ShareTrackingService trackingService, ShareConfigService shareConfigService) {
        this.trackingService = trackingService;
        this.shareConfigService = shareConfigService;
    }

    @PostMapping("/track")
    @Operation(summary = "创建分享跟踪", description = "为指定活动创建可追踪的分享链接")
    public ResponseEntity<ApiResponse<ShareTrackingResponse>> createShareTracking(
        @Parameter(description = "活动ID") @RequestParam Long activityId,
        @Parameter(description = "邀请人用户ID") @RequestParam Long inviterUserId,
        @Parameter(description = "分享来源") @RequestParam(required = false, defaultValue = "direct") String source,
        @Parameter(description = "额外参数") @RequestParam(required = false) Map<String, String> params
    ) {
        ShareTrackingResponse response = trackingService.createShareTracking(activityId, inviterUserId, source, params);
        return ResponseEntity.ok(ApiResponse.success(response));
    }

    @GetMapping("/metrics")
    @Operation(summary = "获取分享指标", description = "获取指定活动在时间范围内的分享指标")
    public ResponseEntity<ApiResponse<ShareMetricsResponse>> getShareMetrics(
        @Parameter(description = "活动ID") @RequestParam Long activityId,
        @Parameter(description = "开始时间") @RequestParam(required = false) OffsetDateTime startTime,
        @Parameter(description = "结束时间") @RequestParam(required = false) OffsetDateTime endTime
    ) {
        if (startTime == null) {
            startTime = OffsetDateTime.now().minus(7, ChronoUnit.DAYS);
        }
        if (endTime == null) {
            endTime = OffsetDateTime.now();
        }

        ShareMetricsResponse metrics = trackingService.getShareMetrics(activityId, startTime, endTime);
        return ResponseEntity.ok(ApiResponse.success(metrics));
    }

    @GetMapping("/top-links")
    @Operation(summary = "获取热门分享链接", description = "获取分享次数最多的链接列表")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTopShareLinks(
        @Parameter(description = "活动ID") @RequestParam Long activityId,
        @Parameter(description = "返回数量") @RequestParam(required = false, defaultValue = "10") int topN
    ) {
        List<Map<String, Object>> topLinks = trackingService.getTopShareLinks(activityId, topN);
        return ResponseEntity.ok(ApiResponse.success(topLinks));
    }

    @GetMapping("/funnel")
    @Operation(summary = "获取转化漏斗数据", description = "获取分享到点击的转化漏斗分析")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getConversionFunnel(
        @Parameter(description = "活动ID") @RequestParam Long activityId,
        @Parameter(description = "开始时间") @RequestParam(required = false) OffsetDateTime startTime,
        @Parameter(description = "结束时间") @RequestParam(required = false) OffsetDateTime endTime
    ) {
        if (startTime == null) {
            startTime = OffsetDateTime.now().minus(7, ChronoUnit.DAYS);
        }
        if (endTime == null) {
            endTime = OffsetDateTime.now();
        }

        Map<String, Object> funnel = trackingService.getConversionFunnel(activityId, startTime, endTime);
        return ResponseEntity.ok(ApiResponse.success(funnel));
    }

    @GetMapping("/share-meta")
    @Operation(summary = "获取分享元数据", description = "获取用于社交媒体分享的OGP元数据")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getShareMeta(
        @Parameter(description = "活动ID") @RequestParam Long activityId,
        @Parameter(description = "用户ID") @RequestParam Long userId,
        @Parameter(description = "模板名称") @RequestParam(required = false, defaultValue = "default") String template
    ) {
        Map<String, Object> meta = shareConfigService.getShareMeta(activityId, userId, template);
        return ResponseEntity.ok(ApiResponse.success(meta));
    }

    @PostMapping("/register-source")
    @Operation(summary = "记录分享来源", description = "从外部系统记录分享来源数据")
    public ResponseEntity<ApiResponse<Void>> registerShareSource(
        @Parameter(description = "活动ID") @RequestParam Long activityId,
        @Parameter(description = "用户ID") @RequestParam Long userId,
        @Parameter(description = "来源渠道") @RequestParam String channel,
        @Parameter(description = "额外参数") @RequestParam(required = false) Map<String, String> params
    ) {
        Map<String, String> allParams = params != null ? new java.util.HashMap<>(params) : new java.util.HashMap<>();
        allParams.put("channel", channel);
        allParams.put("registered_at", OffsetDateTime.now().toString());

        trackingService.createShareTracking(activityId, userId, channel, allParams);
        return ResponseEntity.ok(ApiResponse.success(null));
    }
}
