using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;

namespace TeleWave.Application.Programming.Groups.SetGroupItemWeight;

public sealed class SetGroupItemWeightCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<SetGroupItemWeightCommand, Result>
{
    public async Task<Result> Handle(
        SetGroupItemWeightCommand command,
        CancellationToken cancellationToken
    )
    {
        var group = await dbContext
            .Groups.Include(g => g.Items)
            .FirstOrDefaultAsync(g => g.Id == command.GroupId, cancellationToken);
        if (group is null)
            return Result.Failure(GroupErrors.NotFound);

        // Вес не влияет на объём контента — статистику пересчитывать незачем.
        return group.SetWeight(command.ItemId, command.Weight)
            ? Result.Success()
            : Result.Failure(GroupErrors.ItemNotFound);
    }
}
