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

namespace TeleWave.Application.Programming.Groups.RemoveGroupItem;

public sealed class RemoveGroupItemCommandHandler(IAppDbContext dbContext, GroupStatsService stats)
    : ICommandHandler<RemoveGroupItemCommand, Result>
{
    public async Task<Result> Handle(
        RemoveGroupItemCommand 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);

        if (!group.RemoveItem(command.ItemId))
            return Result.Failure(GroupErrors.ItemNotFound);

        await stats.RecomputeAsync(group, cancellationToken);
        return Result.Success();
    }
}
