using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.DonationAlert.GetConfigByToken;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var channelID = await db.Channel
            .AsNoTracking()
            .Where(c => c.WidgetToken == request.WidgetToken && c.IsActive)
            .Select(c => c.ID)
            .FirstOrDefaultAsync(ct);

        if (channelID == 0)
        {
            return new Response([]);
        }

        var list = await db.DonationAlertConfig
            .AsNoTracking()
            .Where(c => c.ChannelID == channelID && c.IsActive)
            .OrderBy(c => c.Amount)
            .Select(c => new ConfigItem(
                c.ID, c.Title, c.Amount, c.MatchType, c.Message,
                c.PlayDelaySec, c.DisplayDurationSec,
                c.PopupEffect, c.TextEffect,
                c.NicknameFontFamily, c.NicknameFontSize, c.NicknameFontColor,
                c.AmountFontFamily, c.AmountFontSize, c.AmountFontColor,
                c.MessageFontFamily, c.MessageFontSize, c.MessageFontColor,
                c.TemplateFontFamily, c.TemplateFontSize, c.TemplateFontColor,
                c.EnableImage, c.ImageUrl,
                c.EnableSound, c.SoundUrl,
                c.IsActive
            ))
            .ToListAsync(ct);

        return new Response(list);
    }
}