using Microsoft.EntityFrameworkCore;

namespace NetinaShop.Repository.Handlers.Addresses;

public class GetUserAddressesQueryHandler : IRequestHandler<GetUserAddressesQuery, List<UserAddressSDto>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;

    public GetUserAddressesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
    {
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
    }
    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);

    }
}