package com.kt.event.participation.presentation.controller;

import com.kt.event.common.dto.ApiResponse;
import com.kt.event.common.dto.PageResponse;
import com.kt.event.participation.application.dto.DrawWinnersRequest;
import com.kt.event.participation.application.dto.DrawWinnersResponse;
import com.kt.event.participation.application.dto.ParticipationResponse;
import com.kt.event.participation.application.service.WinnerDrawService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 당첨자 추첨 컨트롤러
 *
 * @author Digital Garage Team
 * @since 2025-01-24
 */
@Slf4j
@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/api/v1")
@RequiredArgsConstructor
public class WinnerController {

    private final WinnerDrawService winnerDrawService;

    /**
     * 당첨자 추첨
     * POST /events/{eventId}/draw-winners
     */
    @PostMapping("/events/{eventId}/draw-winners")
    public ResponseEntity<ApiResponse<DrawWinnersResponse>> drawWinners(
        @PathVariable String eventId,
        @Valid @RequestBody DrawWinnersRequest request) {

        log.info("당첨자 추첨 요청 - eventId: {}, winnerCount: {}", eventId, request.getWinnerCount());
        DrawWinnersResponse response = winnerDrawService.drawWinners(eventId, request);

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

    /**
     * 당첨자 목록 조회
     * GET /events/{eventId}/winners
     */
    @Operation(
        summary = "당첨자 목록 조회",
        description = "이벤트의 당첨자 목록을 페이징하여 조회합니다. " +
                     "정렬 가능한 필드: winnerRank(기본값), wonAt, participantId, name, phoneNumber, bonusEntries"
    )
    @GetMapping("/events/{eventId}/winners")
    public ResponseEntity<ApiResponse<PageResponse<ParticipationResponse>>> getWinners(
        @Parameter(description = "이벤트 ID", example = "evt_20250124_001")
        @PathVariable String eventId,

        @ParameterObject
        @PageableDefault(size = 20, sort = "winnerRank", direction = Sort.Direction.ASC)
        Pageable pageable) {

        log.info("당첨자 목록 조회 요청 - eventId: {}", eventId);
        PageResponse<ParticipationResponse> response = winnerDrawService.getWinners(eventId, pageable);

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