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

namespace TeleWave.Application.Library.Collections.AddCollectionShow;

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

        if (!await dbContext.Shows.AnyAsync(s => s.Id == command.ShowId, cancellationToken))
            return Result.Failure(ShowErrors.NotFound);

        return collection.AddShow(command.ShowId) is null
            ? Result.Failure(CollectionErrors.ShowAlreadyAdded)
            : Result.Success();
    }
}
