namespace Netina.Repository.Handlers.Addresses;

public class GetUserAddressesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
    : IRequestHandler<GetUserAddressesQuery, List<UserAddressSDto>>
{
    public async Task<List<UserAddressSDto>> Handle(GetUserAddressesQuery request, CancellationToken cancellationToken)
    {
        Guid userId;
        if (request.UserId != null)
            userId = request.UserId.Value;
        else
        {
            if (currentUserService.UserId == null)
                throw new AppException("User id notfound", ApiResultStatusCode.BadRequest);
            if (!Guid.TryParse(currentUserService.UserId, out userId))
                throw new AppException("User id wrong", ApiResultStatusCode.BadRequest);
        }

        return await repositoryWrapper.SetRepository<UserAddress>()
            .TableNoTracking
            .Where(ua => ua.UserId == userId)
            .Select(UserAddressMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);

    }
}