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

namespace TeleWave.Application.Broadcast.GetChannel;

public sealed class GetChannelQueryHandler(IAppDbContext dbContext)
    : IQueryHandler<GetChannelQuery, Result<ChannelDto>>
{
    public async Task<Result<ChannelDto>> Handle(
        GetChannelQuery query,
        CancellationToken cancellationToken
    )
    {
        // Что и когда идёт в эфире, лежит в шаблоне сетки и запрашивается отдельно
        // (GetChannelTemplateQuery) — здесь только собственные свойства канала.
        var channel = await dbContext
            .Channels.AsNoTracking()
            .Include(c => c.BumperTemplates)
                .ThenInclude(t => t.Variants)
            .AsSplitQuery()
            .FirstOrDefaultAsync(c => c.Id == query.Id, cancellationToken);
        if (channel is null)
            return Result.Failure<ChannelDto>(ChannelErrors.NotFound);

        var bumperTemplates = channel
            .BumperTemplates.OrderBy(t => t.Position)
            .Select(t => new BumperTemplateDto(
                t.Id,
                t.Position,
                t.IsDefault,
                t.Name,
                t.BackgroundColor,
                t.BackgroundColor2,
                t.AccentColor,
                t.TextColor,
                t.BackgroundImageId,
                t.AudioExtension is not null,
                t.AudioDurationSeconds,
                t.Variants.OrderBy(v => v.Position)
                    .Select(v => new BumperTextVariantDto(
                        v.Id,
                        v.Position,
                        v.Name,
                        v.Kind,
                        v.NowLabel,
                        v.NextLabel,
                        v.Line1,
                        v.Line2,
                        v.Trigger,
                        v.Weight
                    ))
                    .ToList()
            ))
            .ToList();

        return Result.Success(
            new ChannelDto(
                channel.Id,
                channel.Name,
                channel.Slug,
                channel.IsEnabled,
                channel.Number,
                channel.UtcOffsetMinutes,
                channel.DayStartTime,
                channel.TemplateId,
                channel.BumpersEnabled,
                new BumperSettingsDto(channel.BumperFont, channel.BumperSelection),
                bumperTemplates,
                channel.FillerAssetId,
                new ViewerSettingsDto(
                    channel.LogoImageId,
                    channel.LogoCorner,
                    channel.LogoOpacity,
                    channel.ShowClock,
                    channel.AnalogFilterStrength
                )
            )
        );
    }
}
