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

namespace TeleWave.Application.Broadcast.UpdateViewerSettings;

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

        if (
            command.LogoImageId is { } imageId
            && !await dbContext.Images.AnyAsync(i => i.Id == imageId, cancellationToken)
        )
            return Result.Failure(ChannelErrors.AssetNotFound);

        channel.UpdateViewerSettings(
            command.LogoImageId,
            command.LogoCorner,
            command.LogoOpacity,
            command.ShowClock,
            command.AnalogFilterStrength
        );
        return Result.Success();
    }
}
