using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Domain.Entities.Donations;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.DonationAlert.SaveConfig;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command r, CancellationToken ct)
    {
        if (r.ID.HasValue)
        {
            var config = await db.DonationAlertConfig.FirstOrDefaultAsync(c => c.ID == r.ID.Value && c.ChannelID == r.ChannelID, ct);
            if (config is null)
            {
                throw new KeyNotFoundException("설정을 찾을 수 없습니다.");
            }

            config.Update(
                r.Title, r.Amount, r.MatchType, r.Message,
                r.PlayDelaySec, r.DisplayDurationSec,
                r.PopupEffect, r.TextEffect,
                r.NicknameFontFamily, r.NicknameFontSize, r.NicknameFontColor,
                r.AmountFontFamily, r.AmountFontSize, r.AmountFontColor,
                r.MessageFontFamily, r.MessageFontSize, r.MessageFontColor,
                r.TemplateFontFamily, r.TemplateFontSize, r.TemplateFontColor,
                r.EnableImage, r.ImageUrl,
                r.EnableSound, r.SoundUrl,
                r.IsActive
            );
        }
        else
        {
            var config = DonationAlertConfig.Create(
                r.ChannelID, r.MemberID, r.Title, r.Amount, r.MatchType, r.Message,
                r.PlayDelaySec, r.DisplayDurationSec,
                popupEffect: r.PopupEffect,
                textEffect: r.TextEffect,
                nicknameFontFamily: r.NicknameFontFamily,
                nicknameFontSize: r.NicknameFontSize,
                nicknameFontColor: r.NicknameFontColor,
                amountFontFamily: r.AmountFontFamily,
                amountFontSize: r.AmountFontSize,
                amountFontColor: r.AmountFontColor,
                messageFontFamily: r.MessageFontFamily,
                messageFontSize: r.MessageFontSize,
                messageFontColor: r.MessageFontColor,
                templateFontFamily: r.TemplateFontFamily,
                templateFontSize: r.TemplateFontSize,
                templateFontColor: r.TemplateFontColor,
                enableImage: r.EnableImage,
                imageUrl: r.ImageUrl,
                enableSound: r.EnableSound,
                soundUrl: r.SoundUrl
            );

            db.DonationAlertConfig.Add(config);
        }

        await db.SaveChangesAsync(ct);
    }
}