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

namespace TeleWave.Application.Library.Collections.ReorderCollection;

public sealed class ReorderCollectionCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<ReorderCollectionCommand, Result>
{
    public async Task<Result> Handle(
        ReorderCollectionCommand command,
        CancellationToken cancellationToken
    )
    {
        var collection = await dbContext
            .Collections.Include(c => c.Items)
            .FirstOrDefaultAsync(c => c.Id == command.CollectionId, cancellationToken);
        if (collection is null)
            return Result.Failure(CollectionErrors.NotFound);

        collection.Reorder(command.ShowIdsInOrder);
        return Result.Success();
    }
}
