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

namespace TeleWave.Application.Broadcast.Bumpers;

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

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

        // Незнакомый плейсхолдер ловим здесь: в эфире он превратился бы в пустоту, и заметить это
        // было бы уже некому.
        var unknown = command
            .Input.Lines.SelectMany(l => BumperPlaceholders.UnknownTokens(l.Text))
            .Distinct(StringComparer.Ordinal)
            .ToList();
        if (unknown.Count > 0)
            return Result.Failure(BumperErrors.UnknownPlaceholders(unknown));

        variant.Update(
            command.Input.Name,
            command.Input.Trigger,
            command.Input.Background,
            command.Input.Weight,
            command.Input.BackgroundClipShowId
        );
        variant.SetLines(
            command.Input.Lines.Select(
                (line, index) => BumperLine.Create(index, line.Style, line.Color, line.Text)
            )
        );

        return Result.Success();
    }
}
