using FluentResults;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Messaging;
using NexusReader.Data.Persistence;

namespace NexusReader.Application.Commands.User;

public class UpdateThemeCommandHandler : ICommandHandler<UpdateThemeCommand>
{
    private readonly IDbContextFactory<AppDbContext> _dbContextFactory;

    public UpdateThemeCommandHandler(IDbContextFactory<AppDbContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }

    public async Task<Result> Handle(UpdateThemeCommand request, CancellationToken cancellationToken)
    {
        try
        {
            using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
            var user = await dbContext.Users
                .AsTracking()
                .FirstOrDefaultAsync(u => u.Id == request.UserId, cancellationToken);
                
            if (user == null)
            {
                return Result.Fail("User not found.");
            }

            user.ThemePreference = request.Mode;
            await dbContext.SaveChangesAsync(cancellationToken);
            
            return Result.Ok();
        }
        catch (Exception ex)
        {
            return Result.Fail(new Error("Failed to save theme preference in database.").CausedBy(ex));
        }
    }
}
