package me.qwq.doghouse.task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import lombok.extern.slf4j.Slf4j;
import me.qwq.doghouse.entity.Comment;
import me.qwq.doghouse.entity.MailTask;
import me.qwq.doghouse.enums.MailTaskTypeEnum;
import me.qwq.doghouse.service.CommentService;
import me.qwq.doghouse.service.MailService;
import me.qwq.doghouse.service.MailTaskService;

@Component
@Slf4j
public class MailTaskWorker {

    @Autowired
    MailTaskService mailTaskService;

    @Autowired
    MailService mailService;

    @Autowired
    CommentService commentService;

    @Scheduled(fixedDelay = 5000L)
    public void run() {
        for (MailTask task : mailTaskService.pollDueTasks()) {
            if (!mailTaskService.markSending(task)) {
                continue;
            }

            try {
                MailService.MailTaskResult result = mailService.executeMailTask(task);
                if (result == MailService.MailTaskResult.CANCELLED) {
                    mailTaskService.markCancelled(task, "任务已不满足发送条件");
                }
                else {
                    mailTaskService.markSent(task);
                    markCommentMailSentIfFinished(task);
                }
            }
            catch (Exception e) {
                log.error("邮件任务 {} 发送失败", task.getId(), e);
                mailTaskService.markFailed(task, e);
            }
        }
    }

    private void markCommentMailSentIfFinished(MailTask task) {
        if (task.getTaskType() != MailTaskTypeEnum.REPLY_SUBSCRIPTION) {
            return;
        }
        if (mailTaskService.hasOutstandingReplyTasks(task.getCommentId())) {
            return;
        }
        commentService.update(new LambdaUpdateWrapper<Comment>()
                .eq(Comment::getId, task.getCommentId())
                .set(Comment::isMailSent, true));
    }
}
