package de.oaa.xxx.games.chastity.community;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import de.oaa.xxx.user.UserEntity;
import de.oaa.xxx.user.UserRepository;

@RestController
@RequestMapping("/games/chastity/community")
public class BaseCommunityDisplayController {

    private final BaseCommunityDisplayRepository baseCommunityDisplayRepository;
    private final UserRepository userRepository;

    public BaseCommunityDisplayController(BaseCommunityDisplayRepository baseCommunityDisplayRepository,
                                          UserRepository userRepository) {
        this.baseCommunityDisplayRepository = baseCommunityDisplayRepository;
        this.userRepository = userRepository;
    }

    @GetMapping
    public ResponseEntity<Page<BaseCommunityDisplayDTO>> getAllDisplays(
            @PageableDefault(size = 10, sort = "createdAt", direction = Direction.DESC) Pageable pageable) {
        Page<BaseCommunityDisplayEntity> page = baseCommunityDisplayRepository.findAll(pageable);

        Set<UUID> lockeeIds = page.getContent().stream()
                .map(BaseCommunityDisplayEntity::getLockeeId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        Map<UUID, String> nameMap = userRepository.findAllById(lockeeIds).stream()
                .collect(Collectors.toMap(UserEntity::getUserId, UserEntity::getName));

        Page<BaseCommunityDisplayDTO> result = page.map(e ->
                e.toBaseCommunityDisplay(nameMap.getOrDefault(e.getLockeeId(), "")));

        return ResponseEntity.ok(result);
    }
}
