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

namespace TeleWave.Application.Programming.Groups.ReorderGroup;

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

        group.Reorder(command.ItemIdsInOrder);
        return Result.Success();
    }
}
