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

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import de.oaa.xxx.games.chastity.cardlock.CardlockRepository;
import de.oaa.xxx.games.chastity.tasks.AssignedTaskEntity;
import de.oaa.xxx.games.chastity.tasks.AssignedTaskRepository;
import de.oaa.xxx.games.chastity.tasks.Task;
import de.oaa.xxx.social.SystemMessageService;
import de.oaa.xxx.social.entity.MessageCause;

@Component
public class KeyholderTaskChoiceScheduler {

    private static final Logger LOG = LoggerFactory.getLogger(KeyholderTaskChoiceScheduler.class);

    private final KeyholderTaskChoiceRepository keyholderTaskChoiceRepository;
    private final CardlockRepository cardlockRepository;
    private final AssignedTaskRepository assignedTaskRepository;
    private final SystemMessageService systemMessageService;

    public KeyholderTaskChoiceScheduler(KeyholderTaskChoiceRepository keyholderTaskChoiceRepository,
                                        CardlockRepository cardlockRepository,
                                        AssignedTaskRepository assignedTaskRepository,
                                        SystemMessageService systemMessageService) {
        this.keyholderTaskChoiceRepository = keyholderTaskChoiceRepository;
        this.cardlockRepository            = cardlockRepository;
        this.assignedTaskRepository        = assignedTaskRepository;
        this.systemMessageService          = systemMessageService;
    }

    @Scheduled(fixedDelay = 60_000)
    @Transactional
    public void processExpiredChoices() {
        var expired = keyholderTaskChoiceRepository
                .findByActiveTrueAndExpiresAtBefore(LocalDateTime.now());

        for (var choice : expired) {
            LOG.debug("Processing expired keyholder task choice {}", choice.getChoiceId());

            var lockOpt = cardlockRepository.findById(choice.getLockId());
            if (lockOpt.isEmpty()) {
                choice.setActive(false);
                keyholderTaskChoiceRepository.save(choice);
                continue;
            }
            var lock = lockOpt.get();
            List<Task> tasks = lock.getTasks();
            if (tasks == null || tasks.isEmpty()) {
                choice.setActive(false);
                keyholderTaskChoiceRepository.save(choice);
                continue;
            }

            int taskIndex = new Random().nextInt(tasks.size());
            Task task = tasks.get(taskIndex);
            LOG.debug("Keyholder did not choose in time → random task index {}", taskIndex);

            AssignedTaskEntity assigned = new AssignedTaskEntity();
            assigned.setLockId(lock.getLockId());
            assigned.setTaskTitle(task.getTitle());
            assigned.setTaskDescription(task.getDescription());
            assigned.setTaskText(task.getTitle());
            assigned.setTaskMinutes(task.getMinutes());
            assigned.setAssignedAt(LocalDateTime.now());
            assigned.setAcceptDeadline(LocalDateTime.now().plusHours(1));
            assigned.setStatus("PENDING");
            assignedTaskRepository.save(assigned);

            choice.setActive(false);
            keyholderTaskChoiceRepository.save(choice);

            sendMessage(lock.getLockee(),
                    "Dein Keyholder hat nicht rechtzeitig gewählt – eine zufällige Aufgabe wurde vergeben: \"" + task.getTitle() + "\"",
                    "/games/chastity/activelock.html?lockId=" + lock.getLockId());

            if (lock.getKeyholder() != null) {
                sendMessage(lock.getKeyholder(),
                        "Du hast die Aufgabenwahl für \"" + (lock.getName() != null ? lock.getName() : "ein Schloss") + "\" nicht rechtzeitig getroffen. Eine zufällige Aufgabe wurde vergeben.",
                        "/games/chastity/keyholder.html");
            }
        }
    }

    private void sendMessage(UUID toId, String text, String targetUrl) {
        systemMessageService.send(toId, toId, text, targetUrl, MessageCause.GAME_STATE);
    }
}
