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

namespace Application.Features.Api.DonationRemote.GetState;

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)
            .Select(c => c.ID)
            .FirstOrDefaultAsync(ct);

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

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

        var queue = await db.DonationAlert.AsNoTracking()
            .Where(a => a.Donation!.ChannelID == channelID
                     && a.Status <= AlertStatus.Playing)
            .OrderBy(a => a.CreatedAt)
            .Select(a => new AlertQueueItem(
                a.ID, a.DonationID, a.Status,
                a.SponsorMemberID, a.Donation!.SendName, a.Donation.Amount,
                a.Donation.Message, a.CreatedAt
            ))
            .ToListAsync(ct);

        return new Response(
            meta?.IsPaused ?? false,
            meta?.IsAccepting ?? true,
            meta?.IsAudioOnly ?? false,
            meta?.IsVideoOnly ?? false,
            queue
        );
    }
}