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

namespace Application.Features.Api.DonationRemote.SkipCurrent;

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

        if (channelID == 0)
        {
            return;
        }

        var playing = await db.DonationAlert.Where(a => a.Donation!.ChannelID == channelID && a.Status == AlertStatus.Playing).FirstOrDefaultAsync(ct);
        if (playing is null)
        {
            return;
        }

        playing.MarkSkipped();
        await db.SaveChangesAsync(ct);
    }
}