package com.qqchen.deploy.backend.system.listener;

import com.qqchen.deploy.backend.framework.enums.ResponseCode;
import com.qqchen.deploy.backend.framework.exception.BusinessException;
import com.qqchen.deploy.backend.notification.dto.WeworkSendNotificationRequest;
import com.qqchen.deploy.backend.notification.entity.NotificationChannel;
import com.qqchen.deploy.backend.notification.enums.WeworkMessageTypeEnum;
import com.qqchen.deploy.backend.notification.repository.INotificationChannelRepository;
import com.qqchen.deploy.backend.notification.service.INotificationSendService;
import com.qqchen.deploy.backend.system.entity.SystemRelease;
import com.qqchen.deploy.backend.system.repository.ISystemReleaseRepository;
import com.qqchen.deploy.backend.system.service.ISystemReleaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 系统版本发布启动监听器
 * 应用启动完成后，自动发送最新版本通知
 */
@Slf4j
@Component
public class SystemReleaseStartupListener {

    @Autowired
    private ISystemReleaseRepository releaseRepository;

    @Autowired
    private ISystemReleaseService releaseService;

    @Autowired
    private INotificationChannelRepository notificationChannelRepository;

    @Autowired
    private INotificationSendService notificationSendService;

    @Value("${deploy.notification.release.channel-id}")
    private Long notificationChannelId;

    /**
     * 应用启动完成事件监听
     */
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        try {
            log.info("========================================");
            log.info("检查是否有未通知的版本发布记录...");
            
            // 查询最新的未通知版本（按版本号降序）
            SystemRelease latestRelease = releaseRepository
                .findFirstByNotifiedFalseAndDeletedFalseOrderByReleaseVersionDesc();
            
            if (latestRelease != null) {
                log.info("发现未通知的版本发布记录");
                log.info("版本号: {}", latestRelease.getReleaseVersion());
                log.info("模块: {}", latestRelease.getModule());
                
                // 发送版本发布通知
                sendReleaseNotification(latestRelease);
                
                // 标记为已通知
                releaseService.markAsNotified(latestRelease.getId());
                
                log.info("版本发布通知已发送并标记");
            } else {
                log.debug("没有未通知的版本发布记录");
            }
            
            log.info("========================================");
            
        } catch (Exception e) {
            log.error("版本发布通知处理失败", e);
        }
    }

    /**
     * 发送版本发布通知
     */
    private void sendReleaseNotification(SystemRelease release) {
        try {
            // 查询通知渠道
            NotificationChannel channel = notificationChannelRepository.findById(notificationChannelId)
                .orElseThrow(() -> new BusinessException(ResponseCode.DATA_NOT_FOUND, 
                    new Object[]{"通知渠道ID=" + notificationChannelId + "不存在"}));
            
            // 准备通知内容（加上版本号）
            String changes = release.getChanges() != null ? release.getChanges() : "暂无变更内容";
            String message = String.format("版本号：%s\n\n%s", release.getReleaseVersion(), changes);
            
            log.info("发送版本发布通知（v{}）：\n{}", release.getReleaseVersion(), message);
            
            // 创建企微通知请求
            WeworkSendNotificationRequest request = new WeworkSendNotificationRequest();
            request.setContent(message);
            request.setTitle("系统版本上线通知");
            request.setMessageType(WeworkMessageTypeEnum.TEXT);
            
            // 发送通知
            notificationSendService.send(channel, request);
            
            log.info("版本发布通知发送成功");
            
        } catch (Exception e) {
            log.error("发送版本发布通知失败", e);
        }
    }
}
