package com.qqchen.deploy.backend.deploy.service.impl;

import com.qqchen.deploy.backend.deploy.enums.ExternalSystemSyncStatus;
import com.qqchen.deploy.backend.deploy.enums.JenkinsSyncType;
import com.qqchen.deploy.backend.deploy.repository.IJenkinsSyncHistoryRepository;
import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import com.qqchen.deploy.backend.deploy.entity.JenkinsSyncHistory;
import com.qqchen.deploy.backend.deploy.dto.JenkinsSyncHistoryDTO;
import com.qqchen.deploy.backend.deploy.query.JenkinsSyncHistoryQuery;
import com.qqchen.deploy.backend.deploy.service.IJenkinsSyncHistoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Jenkin同步日志 Service实现
 */
@Slf4j
@Service
public class JenkinsSyncHistoryServiceImpl extends BaseServiceImpl<JenkinsSyncHistory, JenkinsSyncHistoryDTO, JenkinsSyncHistoryQuery, Long> implements IJenkinsSyncHistoryService {

    @Resource
    private IJenkinsSyncHistoryRepository jenkinsSyncHistoryRepository;

    @Override
    public void saveOrUpdateHistory(JenkinsSyncHistoryDTO syncHistory) {
        LocalDateTime now = LocalDateTime.now();
        
        // 如果是新建的同步历史记录（开始同步时）
        if (syncHistory.getId() == null && syncHistory.getNumber() == null) {
            syncHistory.setNumber(generateSyncHistoryNumber(syncHistory.getSyncType(), syncHistory.getExternalSystemId()));
            syncHistory.setStartTime(now);
            jenkinsSyncHistoryRepository.save(super.converter.toEntity(syncHistory));
            return;
        }
        
        // 查找已存在的记录
        JenkinsSyncHistory existingHistory = jenkinsSyncHistoryRepository.findByNumber(syncHistory.getNumber());
        if (existingHistory != null) {
            // 如果状态是SUCCESS或FAILED，设置结束时间
            if (ExternalSystemSyncStatus.SUCCESS.equals(syncHistory.getStatus()) 
                || ExternalSystemSyncStatus.FAILED.equals(syncHistory.getStatus())) {
                existingHistory.setEndTime(now);
            }
            existingHistory.setStatus(syncHistory.getStatus());
            existingHistory.setErrorMessage(syncHistory.getErrorMessage());
            jenkinsSyncHistoryRepository.save(existingHistory);
        }
    }

    /**
     * 生成同步历史编号
     * 格式：{同步类型}_{年月日时分秒}_{系统ID}
     * 例如：VIEW_20231220123456_1
     *
     * @param syncType 同步类型
     * @param externalSystemId 外部系统ID
     * @return 生成的编号
     */
    private String generateSyncHistoryNumber(JenkinsSyncType syncType, Long externalSystemId) {
        return String.format("%s_%s_%d",
            syncType.name(),
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
            externalSystemId);
    }
}