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

namespace TeleWave.Application.Broadcast.Bumpers;

public sealed class SetBumperTemplateBackgroundCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<SetBumperTemplateBackgroundCommand, Result>
{
    public async Task<Result> Handle(
        SetBumperTemplateBackgroundCommand command,
        CancellationToken cancellationToken
    )
    {
        var template = await BumperTemplateLoader.LoadAsync(
            dbContext,
            command.TemplateId,
            cancellationToken
        );
        if (template is null)
            return Result.Failure(BumperErrors.TemplateNotFound);

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

        template.SetBackgroundImage(command.ImageId);
        return Result.Success();
    }
}
