using CalledIt.Domain.Services;

namespace CalledIt.Api.Authentication;

public class TokenRevocationCacheLoader : IHostedService
{
    private readonly TokenRevocationService _service;
    private readonly ILogger<TokenRevocationCacheLoader> _logger;

    public TokenRevocationCacheLoader(
        TokenRevocationService service,
        ILogger<TokenRevocationCacheLoader> logger)
    {
        _service = service;
        _logger = logger;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        try
        {
            await _service.LoadFromDatabaseAsync(cancellationToken);
        }
#pragma warning disable CA1031 // intentional: don't block host startup if DB is unreachable (e.g. OpenAPI build-time tooling)
        catch (Exception ex)
#pragma warning restore CA1031
        {
            _logger.LogWarning(ex, "Failed to load revoked-token cache from database; continuing with empty cache.");
        }
    }

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