using Microsoft.EntityFrameworkCore;
using AppException = NetinaShop.Common.Models.Exception.AppException;

namespace NetinaShop.Repository.Handlers.Reviews;

public class CreateReviewCommandHandler : IRequestHandler<CreateReviewCommand,ReviewSDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public CreateReviewCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<ReviewSDto> Handle(CreateReviewCommand request, CancellationToken cancellationToken)
    {
        var review = Review.Create(request.Title, request.Comment, request.Rate, request.IsBuyer, request.ProductId,
            request.UserId);
        var product = await _repositoryWrapper.SetRepository<Product>()
            .TableNoTracking
            .FirstOrDefaultAsync(p => p.Id == request.ProductId, cancellationToken);
        if (product == null)
            throw new AppException("Product not found",ApiResultStatusCode.NotFound);

        product.AddRate(request.Rate);

        _repositoryWrapper.SetRepository<Product>().Update(product);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);

        _repositoryWrapper.SetRepository<Review>().Add(review);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);

        return review.AdaptToSDto();
    }
}