package de.oaa.xxx.games.history;

import de.oaa.xxx.user.UserRepository;
import de.oaa.xxx.user.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/gamehistory")
public class GameHistoryController {

    private final UserRepository userRepository;
    private final GameHistoryRepository gameHistoryRepository;
    private final UserService userService;

    public GameHistoryController(UserRepository userRepository, GameHistoryRepository gameHistoryRepository, UserService userService) {
        this.userRepository = userRepository;
        this.gameHistoryRepository = gameHistoryRepository;
        this.userService = userService;
    }

    @GetMapping
    @Transactional(readOnly = true)
    public ResponseEntity<List<Map<String, Object>>> get(@RequestParam("userId") UUID userId, Principal principal) {
        userService.requireUser(principal);

        var result = gameHistoryRepository.findByParticipantUserId(userId).stream()
                .map(e -> {
                    Map<String, Object> item = new LinkedHashMap<>();
                    item.put("historyId",       e.getHistoryId());
                    item.put("gameType",        e.getGameType());
                    item.put("gameName",        e.getGameName() != null ? e.getGameName() : "");
                    item.put("lockName",        e.getGameName() != null ? e.getGameName() : "");
                    item.put("startTime",       e.getStartTime().toString());
                    item.put("unlockTime",      e.getEndTime().toString());
                    item.put("durationMinutes", e.getDurationMinutes());

                    List<Map<String, Object>> participants = e.getParticipants().stream()
                            .map(p -> {
                                Map<String, Object> pm = new LinkedHashMap<>();
                                pm.put("userId", p.getUserId());
                                pm.put("role",   p.getRole());
                                userRepository.findById(p.getUserId()).ifPresent(u -> {
                                    pm.put("name",    u.getName());
                                    pm.put("picture", u.getProfilePicture());
                                });
                                return pm;
                            })
                            .toList();
                    item.put("participants", participants);

                    // Abwärtskompatible Felder für benutzer.html (wird später angepasst)
                    e.getParticipants().stream()
                            .filter(p -> p.getUserId().equals(userId))
                            .findFirst()
                            .ifPresent(own -> item.put("role", own.getRole().name()));

                    e.getParticipants().stream()
                            .filter(p -> !p.getUserId().equals(userId))
                            .findFirst()
                            .ifPresent(partner -> userRepository.findById(partner.getUserId()).ifPresent(u -> {
                                if (GameRole.LOCKEE == partner.getRole()) {
                                    item.put("lockeeName", u.getName());
                                } else if (GameRole.KEYHOLDER == partner.getRole()) {
                                    item.put("keyholderName", u.getName());
                                }
                                item.put("partnerPic", u.getProfilePicture());
                            }));

                    return item;
                }).toList();
        return ResponseEntity.ok(result);
    }
}
