using AppException = Netina.Common.Models.Exception.AppException;

namespace Netina.Repository.Handlers.Reviews;

public class CreateReviewCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
    : IRequestHandler<CreateReviewCommand, Guid>
{
    public async Task<Guid> Handle(CreateReviewCommand request, CancellationToken cancellationToken)
    {
        Guid userId = request.UserId;
        if (userId == default)
        {
            if (!Guid.TryParse(currentUserService.UserId, out userId))
                throw new AppException("User id is wrong", ApiResultStatusCode.BadRequest);
        }
        var review = Review.Create(request.Title, request.Comment, request.Rate, request.IsBuyer, request.ProductId,
            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.Id;
    }
}