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

namespace Application.Features.Api.Notification.GetList;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var query = db.Notification.AsNoTracking().Where(n => n.MemberID == request.MemberID);

        if (request.Type.HasValue)
        {
            query = query.Where(n => n.Type == request.Type.Value);
        }

        var total = await query.CountAsync(ct);
        var unread = await db.Notification.AsNoTracking()
            .CountAsync(n => n.MemberID == request.MemberID && !n.IsRead, ct);

        var list = await query
            .OrderByDescending(n => n.CreatedAt)
            .Skip((request.PageNum - 1) * request.PerPage)
            .Take(request.PerPage)
            .Select(n => new NotificationItem(
                n.ID, n.Type, n.Title, n.Message,
                n.IsRead, n.ActionUrl, n.ImageUrl, n.CreatedAt
            ))
            .ToListAsync(ct);

        return new Response(total, unread, list);
    }
}