using Quartz;

namespace Application.Web;

public class TimerJobManager : ITimerJobManager
{
    private readonly IScheduler _scheduler;

    public TimerJobManager(IScheduler scheduler)
    {
        _scheduler = scheduler;
    }

    public async Task CreateAndStartTask(string jobId, string group, string cronExpression)
    {
        // 创建作业
        var job = JobBuilder.Create<AutoJob>()
            .WithIdentity(jobId, group)
            .Build();

        // 创建触发器
        var trigger = TriggerBuilder.Create()
            .WithIdentity($"{jobId}_trigger", group)
            .WithCronSchedule(cronExpression)
            .Build();

        // 安排作业
        await _scheduler.ScheduleJob(job, trigger);

        // 启动调度器（如果尚未启动）
        if (!_scheduler.IsStarted)
        {
            await _scheduler.Start();
        }
    }

    public async Task PauseTask(string jobId)
    {
        await _scheduler.PauseJob(new JobKey(jobId, "default"));
    }

    public async Task ResumeTask(string jobId, string group)
    {
        await _scheduler.ResumeJob(new JobKey(jobId, group));
    }

    public async Task DeleteTask(string jobId, string group)
    {
        await _scheduler.DeleteJob(new JobKey(jobId, group));
    }

    public async Task DeleteTask(string jobId)
    {
        await _scheduler.DeleteJob(new JobKey(jobId));
    }
}