using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;
using TeleWave.Domain.Broadcast;
using TeleWave.Domain.Programming;

namespace TeleWave.Application.Broadcast.CreateChannel;

public sealed class CreateChannelCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<CreateChannelCommand, Result<Guid>>
{
    public async Task<Result<Guid>> Handle(
        CreateChannelCommand command,
        CancellationToken cancellationToken
    )
    {
        var slugTaken = await dbContext.Channels.AnyAsync(
            c => c.Slug == command.Slug,
            cancellationToken
        );
        if (slugTaken)
            return Result.Failure<Guid>(ChannelErrors.DuplicateSlug);

        var channel = Channel.Create(command.Name, command.Slug, DateTimeOffset.UtcNow);

        // Канал без шаблона вещать не может, поэтому шаблон с фоновым слоем заводится сразу.
        var template = ScheduleTemplate.Create(channel.Id, command.Name);
        channel.SetTemplate(template.Id);

        dbContext.Channels.Add(channel);
        dbContext.ScheduleTemplates.Add(template);
        return Result.Success(channel.Id);
    }
}
