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

namespace Application.Features.Admin.Forum.BoardManager.GetAll;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var items = await db.BoardManager
            .AsNoTracking()
            .Include(x => x.Member)
            .Where(c => c.BoardID == request.BoardID)
            .OrderByDescending(c => c.ID)
            .Select(c => new
            {
                c.ID,
                c.BoardID,
                c.MemberID,
                MemberEmail = c.Member.Email,
                MemberFullName = c.Member.FullName,
                c.CanEdit,
                c.CanDelete,
                c.UpdatedAt,
                c.CreatedAt
            })
            .ToListAsync(ct);

        return new Response(
            items.Count,
            [..items.Select(c => new Response.Row(
                c.ID,
                c.BoardID,
                c.MemberID,
                c.MemberEmail,
                c.MemberFullName,
                c.CanEdit,
                c.CanDelete,
                c.UpdatedAt.GetDateAt(),
                c.CreatedAt.GetDateAt()
            ))]);
    }
}