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

namespace TeleWave.Application.Broadcast.Bumpers;

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

        var template = channel.FindBumperTemplate(command.TemplateId);
        if (template is null)
            return Result.Failure(ChannelErrors.BumperTemplateNotFound);

        var variant = template.FindVariant(command.VariantId);
        if (variant is null)
            return Result.Failure(ChannelErrors.BumperTextVariantNotFound);

        variant.Update(
            command.Name.Trim(),
            new BumperTextContent(
                command.Kind,
                command.NowLabel,
                command.NextLabel,
                command.Line1,
                command.Line2
            ),
            command.Trigger,
            command.Weight
        );
        return Result.Success();
    }
}
