package com.aegis.notification.manager.factory;

import java.util.List;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aegis.common.utils.spring.SpringUtils;
import com.aegis.notification.domain.Notification;
import com.aegis.notification.service.channel.INotificationChannel;

/**
 * 异步通知发送工厂
 * 
 * @author aegis
 */
public class AsyncNotificationFactory {
    
    private static final Logger log = LoggerFactory.getLogger(AsyncNotificationFactory.class);
    
    /**
     * 发送通知任务
     * 
     * @param notification 通知对象
     * @param channels 通知渠道列表
     * @return 任务
     */
    public static TimerTask sendNotification(final Notification notification, final List<INotificationChannel> channels) {
        return new TimerTask() {
            @Override
            public void run() {
                try {
                    // 查找对应的渠道适配器
                    INotificationChannel channel = channels.stream()
                        .filter(c -> c.supports(notification.getChannel()))
                        .findFirst()
                        .orElse(null);
                    
                    if (channel != null) {
                        boolean success = channel.send(notification);
                        if (!success) {
                            log.error("通知发送失败：通知ID={}, 渠道={}", notification.getId(), notification.getChannel());
                        }
                    } else {
                        log.error("不支持的通知渠道：通知ID={}, 渠道={}", notification.getId(), notification.getChannel());
                        // 更新通知状态为失败
                        notification.setStatus("failed");
                        notification.setRemark("不支持的通知渠道：" + notification.getChannel());
                        SpringUtils.getBean(com.aegis.notification.mapper.NotificationMapper.class)
                            .updateNotification(notification);
                    }
                } catch (Exception e) {
                    log.error("通知发送异常：通知ID={}", notification.getId(), e);
                    try {
                        // 更新通知状态为失败
                        notification.setStatus("failed");
                        notification.setRemark("发送异常：" + e.getMessage());
                        SpringUtils.getBean(com.aegis.notification.mapper.NotificationMapper.class)
                            .updateNotification(notification);
                    } catch (Exception ex) {
                        log.error("更新通知状态失败：通知ID={}", notification.getId(), ex);
                    }
                }
            }
        };
    }
}