using Microsoft.Extensions.Options;
using WorkTracker.Configuration;

namespace WorkTracker.Services.Auth;

public sealed class SingleUserSeedService : IHostedService
{
    private readonly IAuthService authService;
    private readonly IOptions<SingleUserOptions> options;
    private readonly ILogger<SingleUserSeedService> logger;

    public SingleUserSeedService(
        IAuthService authService,
        IOptions<SingleUserOptions> options,
        ILogger<SingleUserSeedService> logger)
    {
        this.authService = authService;
        this.options = options;
        this.logger = logger;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        if (!options.Value.SeedOnStartup)
        {
            return;
        }

        try
        {
            await authService.EnsureSeedUserAsync(cancellationToken);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Unable to seed Couchbase Lite single user account {Username}", options.Value.Username);
        }
    }

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