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

namespace Application.Features.Api.MyPage.GetComments;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Result<Response>>
{
    public async Task<Result<Response>> Handle(Query request, CancellationToken ct)
    {
        var page = request.Page < 1 ? 1 : request.Page;
        var perPage = request.PerPage is < 1 or > 50 ? 20 : request.PerPage;

        var query = db.Comment.AsNoTracking().Where(c => c.MemberID == request.MemberID && !c.IsDeleted).OrderByDescending(c => c.ID);
        var total = await query.CountAsync(ct);

        var list = await query
            .Skip((page - 1) * perPage)
            .Take(perPage)
            .Select(c => new
            {
                c.ID,
                c.PostID,
                PostSubject = c.Post.Subject,
                c.BoardID,
                BoardName = c.Board.Name,
                c.Content,
                c.Likes,
                c.CreatedAt
            })
            .ToListAsync(ct);

        var startNum = total - ((page - 1) * perPage);

        return Result.Success(new Response(
            [..list.Select((c, i) => new CommentItem(
                Num: startNum - i,
                c.ID,
                c.PostID,
                c.PostSubject,
                c.BoardID,
                c.BoardName,
                c.Content.Length > 100 ? c.Content[..100] + "..." : c.Content,
                c.Likes,
                c.CreatedAt
            ))],
            total,
            page,
            perPage
        ));
    }
}