package com.bcxin.tenant.open.domains.services.impls;

import com.bcxin.tenant.open.domains.entities.AnalyticsLogEntity;
import com.bcxin.tenant.open.domains.repositories.AnalyticsLogRepository;
import com.bcxin.tenant.open.domains.services.AnalyticsLogService;
import com.bcxin.tenant.open.domains.services.commands.CreateAnalyticsLogCommand;
import com.bcxin.tenant.open.infrastructures.UnitWork;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class AnalyticsLogServiceImpl implements AnalyticsLogService {
    Logger logger = LoggerFactory.getLogger(AnalyticsLogServiceImpl.class);
    private final UnitWork unitWork;
    private final AnalyticsLogRepository analyticsLogRepository;

    public AnalyticsLogServiceImpl(UnitWork unitWork, AnalyticsLogRepository analyticsLogRepository) {
        this.unitWork = unitWork;
        this.analyticsLogRepository = analyticsLogRepository;
    }

    @Override
    public void dispatch(CreateAnalyticsLogCommand command) {
        Collection<AnalyticsLogEntity> analyticsLogs = command.getAnalyticsLogs();
        String transactionId = unitWork.beginTransaction();
        try{
            analyticsLogRepository.batchInsert(analyticsLogs);
            unitWork.commit(transactionId);
        }catch (Exception e){
            logger.error("添加AnalyticsLog记录时发生异常", e);
            unitWork.rollback(transactionId);
            throw e;
        }
    }
}
