package online.wesal.wesal.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import online.wesal.wesal.dto.ApiResponse;
import online.wesal.wesal.dto.DailyChallengeResponse;
import online.wesal.wesal.dto.LeaderboardEntry;
import online.wesal.wesal.dto.PuzzleAttemptRequest;
import online.wesal.wesal.entity.Puzzle;
import online.wesal.wesal.entity.PuzzleAttempt;
import online.wesal.wesal.service.PuzzleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/puzzles")
@CrossOrigin(origins = "*")
@Tag(name = "Puzzles", description = "Wordle puzzle endpoints")
public class PuzzleController {
    
    @Autowired
    private PuzzleService puzzleService;
    
    @GetMapping("/dailyChallenge")
    @Operation(summary = "Get daily challenge", description = "Returns today's Wordle word and user's attempt details")
    public ResponseEntity<ApiResponse<DailyChallengeResponse>> getDailyChallenge() {
        try {
            Puzzle todaysPuzzle = puzzleService.getTodaysPuzzle();
            Optional<PuzzleAttempt> userAttempt = puzzleService.getUserTodaysAttempt();
            
            boolean attempted = userAttempt.isPresent();
            boolean solved = attempted && userAttempt.get().isSolved();
            Integer attempts = attempted ? userAttempt.get().getAttempts() : null;
            LocalDateTime solveTime = attempted ? userAttempt.get().getSubmittedAt() : null;
            
            DailyChallengeResponse response = new DailyChallengeResponse(
                todaysPuzzle.getWord(), 
                attempted, 
                solved, 
                attempts, 
                solveTime
            );
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (RuntimeException e) {
            return ResponseEntity.ok(ApiResponse.error(e.getMessage()));
        }
    }
    
    @PostMapping("/attempt")
    @Operation(summary = "Submit puzzle attempt", description = "Submit user's attempt for today's puzzle")
    public ResponseEntity<ApiResponse<String>> submitAttempt(@Valid @RequestBody PuzzleAttemptRequest request) {
        try {
            puzzleService.submitAttempt(request.getAttempts(), request.getSolved());
            String message = request.getSolved() ? 
                "Congratulations! You solved today's puzzle!" : 
                "Better luck next time!";
            return ResponseEntity.ok(ApiResponse.success(message));
        } catch (RuntimeException e) {
            return ResponseEntity.ok(ApiResponse.error(e.getMessage()));
        }
    }
    
    @GetMapping("/leaderboard")
    @Operation(summary = "Get daily leaderboard", description = "Returns leaderboard for today's puzzle ordered by submission time")
    public ResponseEntity<ApiResponse<List<LeaderboardEntry>>> getLeaderboard() {
        try {
            List<PuzzleAttempt> attempts = puzzleService.getTodaysLeaderboard();
            
            List<LeaderboardEntry> leaderboard = attempts.stream()
                .filter(attempt -> attempt.isSolved())
                .map(attempt -> new LeaderboardEntry(
                    attempt.getUser().getDisplayName(),
                    attempt.getUser().getUsername(),
                    attempt.getUser().getAvatar(),
                    attempt.getAttempts(),
                    attempt.isSolved(),
                    attempt.getSubmittedAt()
                ))
                .collect(Collectors.toList());
            
            return ResponseEntity.ok(ApiResponse.success(leaderboard));
        } catch (RuntimeException e) {
            return ResponseEntity.ok(ApiResponse.error(e.getMessage()));
        }
    }
}