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

namespace Application.Features.Api.MyPage.GetPosts;

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.Post.AsNoTracking().Where(p => p.MemberID == request.MemberID && !p.IsDeleted).OrderByDescending(p => p.ID);
        var total = await query.CountAsync(ct);

        var list = await query
            .Skip((page - 1) * perPage)
            .Take(perPage)
            .Select(p => new
            {
                p.ID,
                p.BoardID,
                BoardName = p.Board.Name,
                p.Subject,
                p.IsSecret,
                p.IsReply,
                p.Views,
                p.Likes,
                p.Comments,
                p.Images,
                p.Medias,
                p.Files,
                p.CreatedAt
            })
            .ToListAsync(ct);

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

        return Result.Success(new Response(
            [..list.Select((p, i) => new PostItem(
                Num: startNum - i,
                p.ID,
                p.BoardID,
                p.BoardName,
                p.Subject,
                p.IsSecret,
                p.IsReply,
                p.Views,
                p.Likes,
                p.Comments,
                p.Images,
                p.Medias,
                p.Files,
                p.CreatedAt
            ))],
            total,
            page,
            perPage
        ));
    }
}