package de.oaa.xxx.location;

import de.oaa.xxx.location.entity.LocationEntity;
import de.oaa.xxx.location.repository.LocationInboxLockRepository;
import de.oaa.xxx.location.repository.LocationRepository;
import de.oaa.xxx.social.entity.MessageEntity;
import de.oaa.xxx.social.repository.MessageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class LocationChatCleanupService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LocationChatCleanupService.class);

    private final LocationRepository         locationRepo;
    private final MessageRepository          messageRepo;
    private final LocationInboxLockRepository lockRepo;

    public LocationChatCleanupService(LocationRepository locationRepo,
                                      MessageRepository messageRepo,
                                      LocationInboxLockRepository lockRepo) {
        this.locationRepo = locationRepo;
        this.messageRepo  = messageRepo;
        this.lockRepo     = lockRepo;
    }

    /** Täglich um 03:00 Uhr: Location-Chats löschen, die seit mehr als einem Monat inaktiv sind. */
    @Scheduled(cron = "0 0 3 * * *")
    @Transactional
    public void cleanupInactiveChats() {
        LocalDateTime cutoff = LocalDateTime.now().minusMonths(1);
        List<LocationEntity> locations = locationRepo.findByVirtualUserIdIsNotNull();
        int deleted = 0;

        for (LocationEntity loc : locations) {
            UUID virtualId = loc.getVirtualUserId();

            // Alle Nachrichten dieser Location (in beide Richtungen)
            List<MessageEntity> allMessages = messageRepo.findAllByUser(virtualId);
            if (allMessages.isEmpty()) continue;

            // Neueste Nachricht pro Gesprächspartner (Besucher)
            Map<UUID, LocalDateTime> latestByVisitor = new HashMap<>();
            for (MessageEntity m : allMessages) {
                UUID visitor = m.getSenderId().equals(virtualId) ? m.getReceiverId() : m.getSenderId();
                latestByVisitor.merge(visitor, m.getSentAt(),
                        (a, b) -> a.isAfter(b) ? a : b);
            }

            for (Map.Entry<UUID, LocalDateTime> entry : latestByVisitor.entrySet()) {
                if (entry.getValue().isBefore(cutoff)) {
                    UUID visitorId = entry.getKey();
                    messageRepo.deleteConversation(virtualId, visitorId);
                    lockRepo.findByLocationIdAndVisitorId(loc.getLocationId(), visitorId)
                            .ifPresent(lockRepo::delete);
                    deleted++;
                    LOGGER.info("Inaktiver Location-Chat gelöscht: location={} visitor={}", loc.getLocationId(), visitorId);
                }
            }
        }

        if (deleted > 0) {
            LOGGER.info("Location-Chat-Cleanup abgeschlossen: {} Konversation(en) gelöscht.", deleted);
        }
    }
}
