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

namespace Application.Features.Api.Forum.Comment.Mention;

public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, List<Response>>
{
    public async Task<List<Response>> Handle(Query request, CancellationToken ct)
    {
        // 해당 게시글에 댓글을 작성한 회원 목록 (본인 제외, DISTINCT)
        var query = db.Comment.AsNoTracking()
            .Include(c => c.Member)
            .Where(c => c.PostID == request.PostID && !c.IsDeleted)
            .Select(c => c.Member)
            .Distinct();

        // 본인 제외
        if (request.MemberID is int memberID)
        {
            query = query.Where(m => m.ID != memberID);
        }

        // 키워드 필터
        if (!string.IsNullOrWhiteSpace(request.Keyword))
        {
            var keyword = request.Keyword.Trim();
            query = query.Where(m => (m.Name != null && m.Name.Contains(keyword)) || m.SID.Contains(keyword));
        }

        var members = await query.Take(10).ToListAsync(ct);

        return members.Select(m => new Response(m.ID, m.SID, m.Name, m.Thumb)).ToList();
    }
}
