package com.lanyuanxiaoyao.leopard.server.controller;

import com.lanyuanxiaoyao.leopard.core.service.TaskService;
import com.lanyuanxiaoyao.leopard.server.service.QuartzService;
import com.lanyuanxiaoyao.service.template.controller.GlobalResponse;
import java.time.LocalDateTime;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("task_schedule")
public class QuartzController {
  private final QuartzService quartzService;
  private final TaskService taskService;

  public QuartzController(QuartzService quartzService, TaskService taskService) {
    this.quartzService = quartzService;
    this.taskService = taskService;
  }

  @PostMapping("save")
  public GlobalResponse<Object> save(@RequestBody SaveItem item) throws SchedulerException {
    quartzService.save(item.templateId(), item.cron());
    return GlobalResponse.responseSuccess();
  }

  @GetMapping("list")
  public GlobalResponse<List<ListItem>> list() throws SchedulerException {
    var list = quartzService.list()
      .stream()
      .map(task -> {
        var template = taskService.getTemplate(task.templateId());
        return new ListItem(
          task.key(),
          template.name(),
          template.description(),
          task.cron(),
          task.status(),
          task.previousFireTime(),
          task.nextFireTime()
        );
      })
      .toList();
    return GlobalResponse.responseSuccess(list);
  }

  @GetMapping("pause/{key}")
  public GlobalResponse<Object> pause(@PathVariable("key") String key) throws SchedulerException {
    quartzService.pause(key);
    return GlobalResponse.responseSuccess();
  }

  @GetMapping("resume/{key}")
  public GlobalResponse<Object> resume(@PathVariable("key") String key) throws SchedulerException {
    quartzService.resume(key);
    return GlobalResponse.responseSuccess();
  }

  @GetMapping("remove/{key}")
  public GlobalResponse<Object> remove(@PathVariable("key") String key) throws SchedulerException {
    quartzService.remove(key);
    return GlobalResponse.responseSuccess();
  }

  public record SaveItem(
    String templateId,
    String cron
  ) {
  }

  public record ListItem(
    String key,
    String templateName,
    String templateDescription,
    String cron,
    Trigger.TriggerState status,
    LocalDateTime previousFireTime,
    LocalDateTime nextFireTime
  ) {
  }
}
