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

namespace TeleWave.Application.Broadcast.UpdateChannelSettings;

public sealed class UpdateChannelSettingsCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<UpdateChannelSettingsCommand, Result>
{
    public async Task<Result> Handle(
        UpdateChannelSettingsCommand 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.FillerAssetId is { } fillerId)
        {
            var exists = await dbContext.MediaAssets.AnyAsync(
                a => a.Id == fillerId,
                cancellationToken
            );
            if (!exists)
                return Result.Failure(ChannelErrors.AssetNotFound);
        }

        channel.UpdateSettings(command.Name, command.IsEnabled, command.FillerAssetId);
        return Result.Success();
    }
}
