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

namespace TeleWave.Application.Broadcast.UpdateChannelTime;

public sealed class UpdateChannelTimeCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<UpdateChannelTimeCommand, Result>
{
    public async Task<Result> Handle(
        UpdateChannelTimeCommand 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.Number is { } number)
        {
            var taken = await dbContext.Channels.AnyAsync(
                c => c.Id != channel.Id && c.Number == number,
                cancellationToken
            );
            if (taken)
                return Result.Failure(ChannelErrors.NumberTaken);
        }

        channel.UpdateTimeSettings(command.Number, command.UtcOffsetMinutes, command.DayStartTime);
        return Result.Success();
    }
}
