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

namespace Application.Features.Api.DonationRemote.UpdateState;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command r, CancellationToken ct)
    {
        var channel = await db.Channel.AsNoTracking()
            .Where(c => c.WidgetToken == r.WidgetToken)
            .Select(c => new { c.ID, c.MemberID })
            .FirstOrDefaultAsync(ct);

        if (channel is null)
        {
            return;
        }

        var meta = await db.DonationMeta.FirstOrDefaultAsync(m => m.ChannelID == channel.ID, ct);

        if (meta is null)
        {
            meta = DonationMeta.Create(channel.ID, channel.MemberID);

            await db.DonationMeta.AddAsync(meta, ct);
            await db.SaveChangesAsync(ct);
        }

        meta.UpdateRemoteState(r.IsPaused, r.IsAudioOnly, r.IsVideoOnly);

        if (r.IsAccepting) {
            meta.StartAccepting();
        } else {
            meta.StopAccepting();
        }

        await db.SaveChangesAsync(ct);
    }
}