using Hc900Crawler.Core.Application.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Hc900Crawler.Infrastructure.Hc900;

public class Hc900HistoryService : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<Hc900HistoryService> _logger;
    private readonly Hc900RealtimeService _realtimeService;
    private readonly int _intervalSeconds;

    public Hc900HistoryService(
        IServiceScopeFactory scopeFactory,
        ILogger<Hc900HistoryService> logger,
        Hc900RealtimeService realtimeService,
        IConfiguration config)
    {
        _scopeFactory    = scopeFactory;
        _logger          = logger;
        _realtimeService = realtimeService;
        _intervalSeconds = config.GetValue<int>("HistoryIntervalSeconds", 60);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("[HistoryService] 시작 — 간격: {Interval}초", _intervalSeconds);

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await Task.Delay(TimeSpan.FromSeconds(_intervalSeconds), stoppingToken);

                if (!_realtimeService.IsConnected)
                {
                    _logger.LogDebug("[HistoryService] HC900 미연결 — 스냅샷 건너뜀");
                    continue;
                }

                using var scope = _scopeFactory.CreateScope();
                var db = scope.ServiceProvider.GetRequiredService<IExperionDbService>();
                // D2: includeDigital 유지, controllerId=null → 전체 컨트롤러
                var count = await db.SnapshotToHistoryAsync(controllerId: null, includeDigital: false);
                _logger.LogInformation("[HistoryService] 스냅샷 저장: {Count}건", count);
            }
            catch (OperationCanceledException) { break; }
            catch (Exception ex)
            {
                _logger.LogError(ex, "[HistoryService] 스냅샷 저장 실패");
            }
        }

        _logger.LogInformation("[HistoryService] 종료");
    }
}
