using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.Notification.MarkRead;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        if (request.NotificationID.HasValue)
        {
            var notification = await db.Notification.FirstOrDefaultAsync(n => n.ID == request.NotificationID.Value && n.MemberID == request.MemberID, ct);

            notification?.MarkRead();
        }
        else
        {
            var unread = await db.Notification.Where(n => n.MemberID == request.MemberID && !n.IsRead).ToListAsync(ct);

            foreach (var n in unread)
            {
                n.MarkRead();
            }
        }

        await db.SaveChangesAsync(ct);
    }
}