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.ParticipationRequest;
import com.kt.event.participation.application.dto.ParticipationResponse;
import com.kt.event.participation.application.service.ParticipationService;
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.HttpStatus;
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 ParticipationController {

    private final ParticipationService participationService;

    /**
     * 이벤트 참여
     * POST /participations/{eventId}/participate
     */
    @PostMapping("/participations/{eventId}/participate")
    public ResponseEntity<ApiResponse<ParticipationResponse>> participate(
        @PathVariable String eventId,
        @Valid @RequestBody ParticipationRequest request) {

        log.info("컨트롤러: 이벤트 참여 요청 시작 - eventId: '{}', phoneNumber: '{}'", eventId, request.getPhoneNumber());

        try {
            log.info("컨트롤러: 서비스 호출 전");
            ParticipationResponse response = participationService.participate(eventId, request);
            log.info("컨트롤러: 서비스 호출 완료 - participantId: {}", response.getParticipantId());

            return ResponseEntity
                .status(HttpStatus.CREATED)
                .body(ApiResponse.success(response));

        } catch (Exception e) {
            log.error("컨트롤러: 예외 발생 - type: {}, message: {}", e.getClass().getSimpleName(), e.getMessage());
            throw e;
        }
    }

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

        @Parameter(description = "매장 방문 여부 필터 (true: 방문자만, false: 미방문자만, null: 전체)")
        @RequestParam(required = false) Boolean storeVisited,

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

        log.info("참여자 목록 조회 요청 - eventId: {}, storeVisited: {}", eventId, storeVisited);
        PageResponse<ParticipationResponse> response =
            participationService.getParticipants(eventId, storeVisited, pageable);

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

    /**
     * 참여자 상세 조회
     * GET /participations/{eventId}/participants/{participantId}
     * GET /events/{eventId}/participants/{participantId} (프론트엔드 호환)
     */
    @GetMapping({"/participations/{eventId}/participants/{participantId}", "/events/{eventId}/participants/{participantId}"})
    public ResponseEntity<ApiResponse<ParticipationResponse>> getParticipant(
        @PathVariable String eventId,
        @PathVariable String participantId) {

        log.info("참여자 상세 조회 요청 - eventId: {}, participantId: {}", eventId, participantId);
        ParticipationResponse response = participationService.getParticipant(eventId, participantId);

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