using ComplianceNFs.Core.Entities; using ComplianceNFs.Core.Application; using ComplianceNFs.Core.Application.Services; namespace ComplianceNFs.Service; public class Worker(ILogger logger, IInvoiceIngestionService ingestionService, IMatchingService matchingService, IComplianceService complianceService, INotificationService notificationService, IArchivingService archivingService) : BackgroundService { private readonly ILogger _logger = logger; private readonly IInvoiceIngestionService _ingestionService = ingestionService; private readonly IMatchingService _matchingService = matchingService; private readonly IComplianceService _complianceService = complianceService; private readonly INotificationService _notificationService = notificationService; private readonly IArchivingService _archivingService = archivingService; protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("Worker starting at: {time}", DateTimeOffset.Now); // Start mail ingestion (starts listening for new mail) await _ingestionService.IngestAsync(); // Subscribe to new invoice events and orchestrate workflow if (_ingestionService is InvoiceIngestionService ingestionImpl) { ingestionImpl.InvoiceProcessed += async invoice => { // 1. Match invoice await _matchingService.MatchAsync(invoice); // 2. Compliance validation await _complianceService.ValidateAsync(invoice); // 3. Notify if needed if (invoice.Status == InvoiceStatus.TaxMismatch || invoice.Status == InvoiceStatus.VolumeMismatch || invoice.Status == InvoiceStatus.PriceMismatch) { await _notificationService.NotifyAsync(invoice, invoice.DiscrepancyNotes ?? "Discrepancy detected"); } // 4. Archive // (Assume raw file is available or can be loaded if needed) // await _archivingService.ArchiveAsync(invoice, rawFile); _logger.LogInformation("Invoice {NumeroNF} processed with status: {Status}", invoice.NumeroNF, invoice.Status); }; } // Keep the worker alive while (!stoppingToken.IsCancellationRequested) { await Task.Delay(1000, stoppingToken); } } }