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 meta = await db.DonationMeta.FirstOrDefaultAsync(m => m.ChannelID == r.ChannelID, ct);

        if (meta is null)
        {
            meta = DonationMeta.Create(r.ChannelID, r.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);
    }
}