package com.easyagents.scheduler.quartz;

import com.easyagents.scheduler.ScheduleException;
import com.easyagents.scheduler.ScheduleId;
import org.quartz.Trigger;
import org.quartz.listeners.TriggerListenerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Instant;

/**
 * 将 Quartz Misfire 投影到通用执行监听器。
 */
final class QuartzMisfireListener extends TriggerListenerSupport {

    private static final Logger log = LoggerFactory.getLogger(QuartzMisfireListener.class);

    private final QuartzRuntime runtime;

    /**
     * 创建 Misfire 监听器。
     *
     * @param runtime 当前节点运行时
     */
    QuartzMisfireListener(QuartzRuntime runtime) {
        this.runtime = runtime;
    }

    /**
     * 返回 Quartz Listener 名称。
     *
     * @return 稳定 Listener 名称
     */
    @Override
    public String getName() {
        return "easyAgentsScheduleMisfireListener";
    }

    /**
     * 转发 Misfire 事件，持久数据损坏时记录明确错误。
     *
     * @param trigger 发生 Misfire 的 Trigger
     */
    @Override
    public void triggerMisfired(Trigger trigger) {
        try {
            ScheduleId scheduleId = QuartzScheduleMapper.toScheduleId(trigger.getJobDataMap());
            Instant expected = trigger.getNextFireTime() == null
                ? null
                : trigger.getNextFireTime().toInstant();
            runtime.notifyMisfired(scheduleId, expected);
        } catch (ScheduleException | IllegalArgumentException exception) {
            log.error("Failed to decode misfired Quartz trigger {}", trigger.getKey(), exception);
        }
    }
}
