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

namespace TeleWave.Application.Broadcast.Bumpers;

public sealed class AddBumperTemplateCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<AddBumperTemplateCommand, Result<Guid>>
{
    public async Task<Result<Guid>> Handle(
        AddBumperTemplateCommand command,
        CancellationToken cancellationToken
    )
    {
        var channel = await dbContext
            .Channels.Include(c => c.BumperTemplates)
            .FirstOrDefaultAsync(c => c.Id == command.ChannelId, cancellationToken);
        if (channel is null)
            return Result.Failure<Guid>(ChannelErrors.NotFound);

        var name = string.IsNullOrWhiteSpace(command.Name)
            ? $"Заставка {channel.BumperTemplates.Count + 1}"
            : command.Name.Trim();
        var template = channel.AddBumperTemplate(name);
        return Result.Success(template.Id);
    }
}
