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

import com.qqchen.deploy.backend.deploy.dto.RepositorySyncHistoryDTO;
import com.qqchen.deploy.backend.deploy.entity.RepositorySyncHistory;
import com.qqchen.deploy.backend.deploy.enums.ExternalSystemSyncStatus;
import com.qqchen.deploy.backend.deploy.enums.RepositorySyncType;
import com.qqchen.deploy.backend.deploy.query.RepositorySyncHistoryQuery;
import com.qqchen.deploy.backend.deploy.repository.IRepositorySyncHistoryRepository;
import com.qqchen.deploy.backend.deploy.service.IRepositorySyncHistoryService;
import com.qqchen.deploy.backend.framework.enums.ResponseCode;
import com.qqchen.deploy.backend.framework.exception.BusinessException;
import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * Git同步历史记录 Service实现
 */
@Slf4j
@Service
public class RepositorySyncHistoryServiceImpl extends BaseServiceImpl<RepositorySyncHistory, RepositorySyncHistoryDTO, RepositorySyncHistoryQuery, Long>
    implements IRepositorySyncHistoryService {

    @Resource
    private IRepositorySyncHistoryRepository repositorySyncHistoryRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RepositorySyncHistoryDTO createSyncHistory(Long externalSystemId, RepositorySyncType syncType) {
        RepositorySyncHistory history = new RepositorySyncHistory();
        history.setNumber(UUID.randomUUID().toString());
        history.setStartTime(LocalDateTime.now());
        history.setStatus(ExternalSystemSyncStatus.RUNNING);
        history.setSyncType(syncType);
        history.setExternalSystemId(externalSystemId);

        history = repositorySyncHistoryRepository.save(history);
        return converter.toDto(history);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSyncHistory(Long id, ExternalSystemSyncStatus status, String errorMessage) {
        RepositorySyncHistory history = repositorySyncHistoryRepository.findById(id)
            .orElseThrow(() -> new BusinessException(ResponseCode.DATA_NOT_FOUND));

        history.setEndTime(LocalDateTime.now());
        history.setStatus(status);
        history.setErrorMessage(errorMessage);

        repositorySyncHistoryRepository.save(history);
    }
} 