namespace TradingBot.Services;

/// <summary>
/// Background service for automatic data persistence on application shutdown
/// </summary>
public class TradingBotBackgroundService : BackgroundService
{
    private readonly TradingBotService _tradingBotService;
    private readonly ILogger<TradingBotBackgroundService> _logger;
    private readonly IHostApplicationLifetime _lifetime;

    public TradingBotBackgroundService(
        TradingBotService tradingBotService,
        ILogger<TradingBotBackgroundService> logger,
        IHostApplicationLifetime lifetime)
    {
        _tradingBotService = tradingBotService;
        _logger = logger;
        _lifetime = lifetime;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("TradingBot Background Service started");

        // Register shutdown handler
        _lifetime.ApplicationStopping.Register(OnShutdown);

        // Keep service running
        await Task.Delay(Timeout.Infinite, stoppingToken);
    }

    private void OnShutdown()
    {
        _logger.LogInformation("Application shutdown detected, saving trade data...");
        
        try
        {
            // Stop bot if running
            if (_tradingBotService.Status.IsRunning)
            {
                _tradingBotService.Stop();
            }
            
            _logger.LogInformation("Trade data saved successfully on shutdown");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error saving data on shutdown");
        }
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("TradingBot Background Service stopping");
        await base.StopAsync(cancellationToken);
    }
}
