namespace CMSMicroservice.Application.UserCQ.Queries.GetJwtToken;
public class GetJwtTokenQueryHandler : IRequestHandler<GetJwtTokenQuery, GetJwtTokenResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly IGenerateJwtToken _generateJwt;

    public GetJwtTokenQueryHandler(IApplicationDbContext context, IGenerateJwtToken generateJwt)
    {
        _context = context;
        _generateJwt = generateJwt;
    }

    public async Task<GetJwtTokenResponseDto> Handle(GetJwtTokenQuery request, CancellationToken cancellationToken)
    {
        var user = await _context.Users
            .Include(u => u.UserContracts)
                .ThenInclude(uc => uc.Contract)
            .Include(u => u.UserRoles)
                .ThenInclude(ur => ur.Role)
            .Include(u => u.ClubMembership)
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(User), request.Id);
        return new GetJwtTokenResponseDto()
        {
            Token = await _generateJwt.GenerateJwtToken(user),
        };
    }
}
