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

namespace Application.Features.Api.Crew.GetCrewMembers;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var crew = await db.Crew.AsNoTracking()
            .FirstOrDefaultAsync(c => c.ID == request.CrewID, ct);

        if (crew is null)
        {
            throw new KeyNotFoundException("크루를 찾을 수 없습니다.");
        }

        var list = await db.CrewMember.AsNoTracking()
            .Where(m => m.CrewID == request.CrewID)
            .OrderBy(m => m.SortOrder)
            .ThenBy(m => m.JoinedAt)
            .Select(m => new CrewMemberItem(
                m.ID, m.MemberID, m.ChannelID, m.Nickname, m.Role,
                m.SortOrder, m.IsActive, m.JoinedAt,
                m.Member != null ? m.Member.Thumb : null,
                m.Channel != null ? m.Channel.Name : null
            ))
            .ToListAsync(ct);

        return new Response(list);
    }
}