package com.mosquito.project.controller;

import com.mosquito.project.domain.Activity;
import com.mosquito.project.dto.CreateActivityRequest;
import com.mosquito.project.dto.UpdateActivityRequest;
import com.mosquito.project.dto.ActivityStatsResponse;
import com.mosquito.project.dto.ActivityGraphResponse;
import com.mosquito.project.dto.ApiResponse;
import com.mosquito.project.service.ActivityService;
import com.mosquito.project.domain.LeaderboardEntry;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.util.List;

@RestController
@RequestMapping("/api/v1/activities")
@Tag(name = "Activity Management", description = "活动管理API")
public class ActivityController {

    private final ActivityService activityService;

    public ActivityController(ActivityService activityService) {
        this.activityService = activityService;
    }

    @PostMapping
    @Operation(summary = "创建活动", description = "创建一个新的推广活动")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "201", description = "活动创建成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    public ResponseEntity<ApiResponse<Activity>> createActivity(@Valid @RequestBody CreateActivityRequest request) {
        Activity createdActivity = activityService.createActivity(request);
        ApiResponse<Activity> response = ApiResponse.success(createdActivity);
        response.setCode(HttpStatus.CREATED.value());
        return new ResponseEntity<>(response, HttpStatus.CREATED);
    }

    @GetMapping
    @Operation(summary = "获取活动列表", description = "获取全部活动列表")
    public ResponseEntity<ApiResponse<List<Activity>>> getActivities() {
        List<Activity> activities = activityService.getAllActivities();
        return ResponseEntity.ok(ApiResponse.success(activities));
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新活动", description = "更新指定活动的详细信息")
    public ResponseEntity<ApiResponse<Activity>> updateActivity(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Valid @RequestBody UpdateActivityRequest request) {
        Activity updatedActivity = activityService.updateActivity(id, request);
        return ResponseEntity.ok(ApiResponse.success(updatedActivity));
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取活动", description = "根据ID获取活动详情")
    public ResponseEntity<ApiResponse<Activity>> getActivityById(@Parameter(description = "活动ID") @PathVariable Long id) {
        Activity activity = activityService.getActivityById(id);
        return ResponseEntity.ok(ApiResponse.success(activity));
    }

    @GetMapping("/{id}/stats")
    @Operation(summary = "获取活动统计", description = "获取活动的参与统计信息")
    public ResponseEntity<ApiResponse<ActivityStatsResponse>> getActivityStats(@Parameter(description = "活动ID") @PathVariable Long id) {
        ActivityStatsResponse stats = activityService.getActivityStats(id);
        return ResponseEntity.ok(ApiResponse.success(stats));
    }

    @GetMapping("/{id}/graph")
    @Operation(summary = "获取活动关系图", description = "获取用户邀请关系图谱")
    public ResponseEntity<ApiResponse<ActivityGraphResponse>> getActivityGraph(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "根用户ID，可选") @RequestParam(name = "rootUserId", required = false) Long rootUserId,
            @Parameter(description = "最大深度，默认3") @RequestParam(name = "maxDepth", required = false, defaultValue = "3") Integer maxDepth,
            @Parameter(description = "限制数量，默认1000") @RequestParam(name = "limit", required = false, defaultValue = "1000") Integer limit) {
        ActivityGraphResponse graph = activityService.getActivityGraph(id, rootUserId, maxDepth, limit);
        return ResponseEntity.ok(ApiResponse.success(graph));
    }

    @GetMapping("/{id}/leaderboard")
    @Operation(summary = "获取排行榜", description = "获取活动邀请排行榜")
    public ResponseEntity<ApiResponse<List<LeaderboardEntry>>> getLeaderboard(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "页码，从0开始") @RequestParam(name = "page", required = false, defaultValue = "0") Integer page,
            @Parameter(description = "每页大小") @RequestParam(name = "size", required = false, defaultValue = "20") Integer size,
            @Parameter(description = "只返回前N名") @RequestParam(name = "topN", required = false) Integer topN) {
        List<LeaderboardEntry> list = activityService.getLeaderboard(id);
        if (topN != null && topN > 0 && topN < list.size()) {
            list = list.subList(0, topN);
        }
        int p = (page == null || page < 0) ? 0 : page;
        int s = (size == null || size < 1) ? 20 : size;
        int from = p * s;
        int total = list.size();
        if (from >= total) {
            return ResponseEntity.ok(ApiResponse.paginated(java.util.Collections.emptyList(), p, s, total));
        }
        int to = Math.min(from + s, total);
        return ResponseEntity.ok(ApiResponse.paginated(list.subList(from, to), p, s, total));
    }

    @GetMapping("/{id}/leaderboard/export")
    @Operation(summary = "导出排行榜", description = "将排行榜导出为CSV格式")
    public ResponseEntity<byte[]> exportLeaderboard(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "只导出前N名") @RequestParam(name = "topN", required = false) Integer topN) {
        String csv = (topN == null) ? activityService.generateLeaderboardCsv(id) : activityService.generateLeaderboardCsv(id, topN);
        byte[] body = csv.getBytes(java.nio.charset.StandardCharsets.UTF_8);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("text/csv; charset=UTF-8"));
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"leaderboard_" + id + ".csv\"");
        return new ResponseEntity<>(body, headers, HttpStatus.OK);
    }
}
