using ladaexpress.vn.Infrastructures.Services;

namespace ladaexpress.vn.Infrastructures.Startup
{
    /// <summary>
    /// Dịch vụ khởi động để load AppConfig vào cache
    /// </summary>
    public class StartupHostedService : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<StartupHostedService> _logger;

        public StartupHostedService(IServiceProvider serviceProvider, ILogger<StartupHostedService> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        /// <summary>
        /// Khởi tạo services khi ứng dụng start
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("Starting application initialization...");

                using (var scope = _serviceProvider.CreateScope())
                {
                    // Load AppConfig into cache
                    var appConfigService = scope.ServiceProvider.GetRequiredService<IAppConfigService>();
                    await appConfigService.LoadConfigsToCacheAsync();

                    // Load ScriptConfig into cache if needed
                    var scriptConfigService = scope.ServiceProvider.GetService<IScriptConfigService>();
                    if (scriptConfigService != null)
                    {
                        // ScriptConfig có thể có method tương tự nếu cần
                        _logger.LogInformation("ScriptConfig service is available");
                    }
                }

                _logger.LogInformation("Application initialization completed successfully");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error during application initialization");
                throw; // Re-throw để ứng dụng không start nếu có lỗi critical
            }
        }

        /// <summary>
        /// Cleanup khi ứng dụng stop
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Application is stopping...");
            return Task.CompletedTask;
        }
    }
}
