using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TakeoutSaaS.Application.Dictionary.Services;
using TakeoutSaaS.Infrastructure.Dictionary.Options;

namespace TakeoutSaaS.Infrastructure.Dictionary.Caching;

/// <summary>
/// 字典缓存预热服务。
/// </summary>
public sealed class CacheWarmupService(
    IServiceScopeFactory scopeFactory,
    IOptions<DictionaryCacheWarmupOptions> options,
    ILogger<CacheWarmupService> logger) : IHostedService
{
    private const int MaxWarmupCount = 10;

    /// <inheritdoc />
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var codes = options.Value.DictionaryCodes
            .Where(code => !string.IsNullOrWhiteSpace(code))
            .Select(code => code.Trim())
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .Take(MaxWarmupCount)
            .ToArray();

        if (codes.Length == 0)
        {
            logger.LogInformation("未配置字典缓存预热列表。");
            return;
        }

        using var scope = scopeFactory.CreateScope();
        var queryService = scope.ServiceProvider.GetRequiredService<DictionaryQueryService>();

        foreach (var code in codes)
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                await queryService.GetMergedDictionaryAsync(code, cancellationToken);
                logger.LogInformation("字典缓存预热完成: {DictionaryCode}", code);
            }
            catch (Exception ex)
            {
                logger.LogWarning(ex, "字典缓存预热失败: {DictionaryCode}", code);
            }
        }
    }

    /// <inheritdoc />
    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
