package de.oaa.xxx.social;

import de.oaa.xxx.social.entity.ProfileVisitEntity;
import de.oaa.xxx.social.repository.ProfileVisitRepository;
import de.oaa.xxx.user.UserEntity;
import de.oaa.xxx.user.UserRepository;
import de.oaa.xxx.user.UserService;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/social/profile-visits")
public class ProfileVisitController {

    private final ProfileVisitRepository profileVisitRepository;
    private final UserRepository userRepository;
    private final UserService userService;

    public ProfileVisitController(ProfileVisitRepository profileVisitRepository,
                                  UserRepository userRepository,
                                  UserService userService) {
        this.profileVisitRepository = profileVisitRepository;
        this.userRepository = userRepository;
        this.userService = userService;
    }

    record VisitorDto(UUID userId, String name, String profilePicture, LocalDateTime visitedAt) {}

    @PostMapping("/{profileId}")
    public ResponseEntity<Void> recordVisit(@PathVariable("profileId") UUID profileId, Principal principal) {
        if (principal == null) return ResponseEntity.ok().build();
        UUID visitorId = userService.requireUser(principal).getUserId();

        // Eigenes Profil nicht tracken
        if (visitorId.equals(profileId)) return ResponseEntity.ok().build();

        // 1-Stunden-Deduplication
        LocalDateTime oneHourAgo = LocalDateTime.now().minusHours(1);
        if (profileVisitRepository.findByProfileIdAndVisitorIdAndVisitedAtAfter(profileId, visitorId, oneHourAgo).isPresent()) {
            return ResponseEntity.ok().build();
        }

        ProfileVisitEntity visit = new ProfileVisitEntity();
        visit.setVisitId(UUID.randomUUID());
        visit.setProfileId(profileId);
        visit.setVisitorId(visitorId);
        visit.setVisitedAt(LocalDateTime.now());
        profileVisitRepository.save(visit);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/my-visitors")
    public ResponseEntity<List<VisitorDto>> getMyVisitors(Principal principal) {
        UUID profileId = userService.requireUser(principal).getUserId();
        List<ProfileVisitEntity> visits = profileVisitRepository.findRecentByProfileId(
                profileId, PageRequest.of(0, 10));

        List<VisitorDto> result = visits.stream()
                .map(v -> {
                    Optional<UserEntity> visitor = userRepository.findById(v.getVisitorId());
                    return visitor.map(u -> new VisitorDto(
                            u.getUserId(), u.getName(), u.getProfilePicture(), v.getVisitedAt()
                    )).orElse(null);
                })
                .filter(Objects::nonNull)
                .toList();

        return ResponseEntity.ok(result);
    }
}
