package com.lanyuanxiaoyao.leopard.server.service;

import com.lanyuanxiaoyao.leopard.core.entity.Task;
import com.lanyuanxiaoyao.leopard.core.repository.TaskRepository;
import com.lanyuanxiaoyao.leopard.server.service.task.TaskMonitorNodes;
import com.lanyuanxiaoyao.service.template.service.SimpleServiceSupport;
import com.yomahub.liteflow.core.FlowExecutor;
import jakarta.transaction.Transactional;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

/**
 * @author lanyuanxiaoyao
 * @version 20250829
 */
@Slf4j
@Service
public class TaskService extends SimpleServiceSupport<Task> {
  private final TaskRepository taskRepository;
  private final TaskTemplateService taskTemplateService;
  private final FlowExecutor flowExecutor;

  public TaskService(TaskRepository repository, TaskTemplateService taskTemplateService, @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") FlowExecutor flowExecutor) {
    super(repository);
    this.taskRepository = repository;
    this.taskTemplateService = taskTemplateService;
    this.flowExecutor = flowExecutor;
  }

  @Transactional(rollbackOn = Throwable.class)
  @EventListener(ApplicationReadyEvent.class)
  public void onApplicationReady() {
    log.warn("更新所有未完成的任务状态为失败");
    taskRepository.updateAllRunningTaskToFailure();
  }

  public void execute(Long templateId, Map<String, Object> params) {
    var template = taskTemplateService.detail(templateId);
    var context = new TaskMonitorNodes.TaskMonitorContext(template);
    flowExecutor.execute2Future(template.getChain(), params, context);
  }

  @Transactional(rollbackOn = Throwable.class)
  public void updateStepById(Integer step, Long id) {
    taskRepository.updateStepById(step, id);
  }
}
