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

namespace TeleWave.Application.Library.Collections.SetCollectionPoster;

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

        if (
            command.ImageId is { } imageId
            && !await dbContext.Images.AnyAsync(i => i.Id == imageId, cancellationToken)
        )
            return Result.Failure(ImageErrors.NotFound);

        collection.SetPosterImage(command.ImageId);
        return Result.Success();
    }
}
