package kz.konturai.parser.service;

import kz.konturai.parser.model.PostingTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

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

@Service
public class PostingSchedulerService {

    private static final Logger logger = LoggerFactory.getLogger(PostingSchedulerService.class);

    private final PostingTaskService postingTaskService;

    @Value("${posting.scheduler.enabled:true}")
    private boolean schedulerEnabled;

    public PostingSchedulerService(PostingTaskService postingTaskService) {
        this.postingTaskService = postingTaskService;
    }

    /**
     * Планировщик, который запускается каждую минуту
     * Проверяет очередь задач и выполняет задачи, у которых наступило время публикации
     */
    @Scheduled(cron = "0 * * * * ?")
    public void checkAndExecutePendingTasks() {
        if (!schedulerEnabled) {
            logger.debug("Posting scheduler is disabled. Skipping task check.");
            return;
        }

        try {
            LocalDateTime now = LocalDateTime.now();
            logger.debug("Checking for pending posting tasks at {}", now);

            // Получаем задачи со статусом pending, у которых publishDate <= текущее время
            List<PostingTask> pendingTasks = postingTaskService.getPendingTasks(now);

            if (pendingTasks.isEmpty()) {
                logger.debug("No pending tasks found for execution");
                return;
            }

            logger.info("Found {} pending task(s) to execute", pendingTasks.size());

            // Выполняем каждую задачу
            for (PostingTask task : pendingTasks) {
                try {
                    logger.info("Executing task {} for platform {} (publish date: {})", 
                            task.getId(), task.getPlatform(), task.getPublishDate());
                    postingTaskService.executeTaskAsync(task.getId());
                } catch (Exception e) {
                    logger.error("Error executing task {}: {}", task.getId(), e.getMessage(), e);
                }
            }

        } catch (Exception e) {
            logger.error("Error in posting scheduler", e);
        }
    }
}

