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

namespace TeleWave.Application.Settings.UpdateSiteSettings;

public sealed class UpdateSiteSettingsCommandHandler(ISiteSettings siteSettings)
    : ICommandHandler<UpdateSiteSettingsCommand, Result>
{
    public async Task<Result> Handle(
        UpdateSiteSettingsCommand command,
        CancellationToken cancellationToken
    )
    {
        // Сохранение выполняет UnitOfWorkBehavior команды.
        await siteSettings.SetRegistrationEnabledAsync(
            command.RegistrationEnabled,
            cancellationToken
        );
        // Нормализуем список языков: без пробелов, в нижнем регистре, пустые отбрасываем.
        var languages = string.Join(
            ',',
            (command.PreferredAudioLanguages ?? string.Empty)
                .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
                .Select(x => x.ToLowerInvariant())
        );
        await siteSettings.SetPreferredAudioLanguagesAsync(languages, cancellationToken);
        await siteSettings.SetChannelNumbersEnabledAsync(
            command.ChannelNumbersEnabled,
            cancellationToken
        );
        return Result.Success();
    }
}
