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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class UnlockCodeHistoryService {

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

    private final UnlockCodeHistoryRepository unlockCodeHistoryRepository;

    public UnlockCodeHistoryService(UnlockCodeHistoryRepository unlockCodeHistoryRepository) {
        this.unlockCodeHistoryRepository = unlockCodeHistoryRepository;
    }

    /**
     * Speichert einen Entsperrcode-Eintrag in einer eigenen Transaktion,
     * damit ein Fehler hier die aufrufende Transaktion nicht zurückrollt.
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void save(UUID userId, UUID lockId, String lockName, String unlockCode, String source) {
        if (unlockCode == null || unlockCode.isBlank()) return;
        try {
            if (unlockCodeHistoryRepository.existsByLockIdAndSourceAndUnlockCode(lockId, source, unlockCode)) return;
            UnlockCodeHistoryEntity entry = new UnlockCodeHistoryEntity();
            entry.setUserId(userId);
            entry.setLockId(lockId);
            entry.setLockName(lockName != null && !lockName.isBlank() ? lockName : "Unbenanntes Lock");
            entry.setUnlockCode(unlockCode);
            entry.setSource(source);
            entry.setReceivedAt(LocalDateTime.now());
            unlockCodeHistoryRepository.save(entry);
            // Nur die letzten 10 behalten
            long count = unlockCodeHistoryRepository.countByUserId(userId);
            if (count > 10) {
                var oldest = unlockCodeHistoryRepository.findByUserIdOrderByReceivedAtAsc(userId);
                for (int i = 0; i < count - 10; i++) {
                    unlockCodeHistoryRepository.delete(oldest.get(i));
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Entsperrcode-Historie konnte nicht gespeichert werden (lockId={}, source={}): {}", lockId, source, e.getMessage());
        }
    }
}
