package de.htwsaar.webshop.service.impl;

import de.htwsaar.webshop.model.ReviewModel;
import de.htwsaar.webshop.repository.ReviewRepository;
import de.htwsaar.webshop.repository.entities.Review;
import de.htwsaar.webshop.service.ArticleService;
import de.htwsaar.webshop.service.ReviewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class ReviewServiceImpl implements ReviewService {
    private final ReviewRepository reviewRepository;
    private final ArticleService articleService;

    @Autowired
    public ReviewServiceImpl(ReviewRepository reviewRepository, ArticleService articleService) {
        this.reviewRepository = reviewRepository;
        this.articleService = articleService;
    }

    @Override
    public Review save(Review review) {
        review.setTimestamp(System.currentTimeMillis());
        return reviewRepository.save(review);
    }

    @Override
    public Review save(UUID articleUuid, int rating, String content) {
        if (articleUuid == null) {
            return null;
        }
        Review review = new Review(null, content, articleService.findByUUID(articleUuid), rating, System.currentTimeMillis());
        return reviewRepository.save(review);
    }

    @Override
    public void delete(Long reviewId) {
        reviewRepository.deleteById(reviewId);
    }

    @Override
    public Review getReviewById(Long reviewId) {
        return reviewRepository.findById(reviewId).orElse(null);
    }

    @Override
    public List<Review> getAllByUUID(UUID uuid) {
        return reviewRepository.getReviewsByArticle_Uuid(uuid);
    }

    @Override
    public ReviewModel toModel(Review review) {
        return new ReviewModel(review.getTimestamp(), review.getRating(), review.getContent());
    }
}
