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

namespace Application.Features.Api.Note.GetInbox;

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

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

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

        var list = await query
            .OrderByDescending(n => n.CreatedAt)
            .Skip((request.PageNum - 1) * request.PerPage)
            .Take(request.PerPage)
            .Select(n => new NoteItem(
                n.ID, n.SenderMemberID,
                n.SenderMemberID == 0 ? "시스템" : (n.Sender != null ? n.Sender.Name : null),
                n.Title, n.IsRead, n.IsSystem, n.CreatedAt
            ))
            .ToListAsync(ct);

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