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

namespace TeleWave.Application.Broadcast.Bumpers;

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

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

        // Врезка могла выбрать этот подблок жёстко — тогда удаление оставило бы её без текста.
        var used = await dbContext.JunctionElements.AnyAsync(
            e => e.BumperVariantId == command.VariantId,
            cancellationToken
        );
        if (used)
            return Result.Failure(BumperErrors.VariantInUse);

        return template.RemoveVariant(command.VariantId)
            ? Result.Success()
            : Result.Failure(BumperErrors.CannotRemoveLastVariant);
    }
}
