using EnvelopeGenerator.WorkerService.Configuration; using EnvelopeGenerator.WorkerService.Services; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Options; namespace EnvelopeGenerator.WorkerService; public class Worker : BackgroundService { private readonly ILogger _logger; private readonly WorkerSettings _settings; private readonly TempFileManager _tempFiles; public Worker( ILogger logger, IOptions settings, TempFileManager tempFiles) { _logger = logger; _settings = settings.Value; _tempFiles = tempFiles; } public override async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Starting EnvelopeGenerator worker..."); _logger.LogInformation("Debug mode: {Debug}", _settings.Debug); ValidateConfiguration(); await EnsureDatabaseConnectionAsync(cancellationToken); await _tempFiles.CreateAsync(cancellationToken); await base.StartAsync(cancellationToken); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("EnvelopeGenerator worker is running. Jobs are scheduled every {Interval} minute(s).", Math.Max(1, _settings.IntervalMinutes)); await Task.Delay(Timeout.Infinite, stoppingToken); } public override async Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Stopping EnvelopeGenerator worker..."); await _tempFiles.CleanupAsync(cancellationToken); await base.StopAsync(cancellationToken); } private void ValidateConfiguration() { if (string.IsNullOrWhiteSpace(_settings.ConnectionString)) { throw new InvalidOperationException("Connection string cannot be empty. Configure 'WorkerSettings:ConnectionString'."); } } private async Task EnsureDatabaseConnectionAsync(CancellationToken cancellationToken) { try { await using var connection = new SqlConnection(_settings.ConnectionString); await connection.OpenAsync(cancellationToken); _logger.LogInformation("Database connection established successfully."); } catch (Exception ex) { _logger.LogError(ex, "Database connection could not be established."); throw; } } }