package ru.nbch.credit_tracker.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import ru.nbch.credit_tracker.entities.dto.UserPackage;
import ru.nbch.credit_tracker.enums.Status;
import ru.nbch.credit_tracker.service.signal.SignalRestService;

import java.util.List;

/**
 * Сервис для завершения обработки пакетов находящихся в статусе PROCESSING
 * Запускается при старте приложения и отрабатывает 1 раз
 */
@Slf4j
@Service
public class UpdateProcessingPackagesService {

    private final SignalService signalService;
    private final SignalRestService signalRestService;
    private final MonitoringErrorProcesingService monitoringErrorProcesingService;

    public UpdateProcessingPackagesService(SignalService signalService,
                                           SignalRestService signalRestService,
                                           MonitoringErrorProcesingService monitoringErrorProcesingService) {
        this.signalService = signalService;
        this.signalRestService = signalRestService;
        this.monitoringErrorProcesingService = monitoringErrorProcesingService;
    }

    public void run() {
        log.info("Start updating processing packages");
        List<UserPackage> packages = signalService.findPackagesOnProcessing();
        for (UserPackage userPackage : packages) {
            log.info("Updating flags for Package {}", userPackage.getPackageName());
            process(userPackage.getId(), userPackage.getPackageName());
        }
        log.info("Finish updating processing packages");
    }

    private void process(Integer packageId, String packageName) {
        try {
            SignalService.UpdateResult updateResult = signalService.updateSubjects(packageId, null);
            if (updateResult.isNoFidsFound()) {
                log.info("No fids found for PackageId: {} PackageName: {}. Package status ON_MONITORING. No registration in signal service.", packageId, packageName);
                signalService.updatePackageStatus(packageId, Status.ON_MONITORING);
                return;
            }
            if (signalRestService.setupMonitoring(packageId)) {
                log.info("Package was successfully registered in signal service. PackageId: {} PackageName: {}", packageId, packageName);
                signalService.updatePackageStatus(packageId, Status.ON_MONITORING);
                monitoringErrorProcesingService.findErrors(packageId);
            } else {
                log.info("Package registration was rejected by signal service. PackageId: {} PackageName: {}", packageId, packageName);
                signalService.updatePackageStatus(packageId, Status.ERROR);
            }
        } catch (Exception e) {
            signalService.updatePackageStatus(packageId, Status.ERROR);
            log.error("Ошибка при поиске фидов или расчете флагов просрочек. Package_id {}", packageId, e);
        }
    }
}
