package kr.co.jinwoosi.clfd.clfd.prod.service;

import kr.co.jinwoosi.clfd.clfd.prod.mapper.ProdLikeMapper;
import kr.co.jinwoosi.clfd.clfd.prod.model.ProdLike;
import kr.co.jinwoosi.clfd.clfd.prod.model.ProdLikeSearch;
import kr.co.jinwoosi.clfd.conts.prod.model.Prod;
import kr.co.jinwoosi.clfd.conts.prod.model.ProdSearch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

@Service
public class ProdLikeService {
    @Autowired
    private ProdLikeMapper prodLikeMapper;
    @Autowired
    private ClfdProdService clfdProdService;

    public ProdLike select(Long prodId, Long userId) {
        ProdLikeSearch prodLikeSearch = new ProdLikeSearch();
        prodLikeSearch.setProdId(prodId);
        prodLikeSearch.setUserId(userId);
        return prodLikeMapper.select(prodLikeSearch);
    }

    public void insert(Long prodId, Long userId) {
        try {
            prodLikeMapper.insert(new ProdLike(prodId, userId));
            ProdSearch prodSearch = new ProdSearch();
            prodSearch.setProdId(prodId);
            Prod prod = clfdProdService.select(prodSearch);
            clfdProdService.plusRcmdNo(prod);
            clfdProdService.update(prod);
        } catch (DuplicateKeyException e) {
            throw new RuntimeException("이미 좋아요를 하였습니다.");
        }
    }

    public void delete(Long prodId, Long userId) {
        if (prodLikeMapper.deleteAndReturnCount(new ProdLike(prodId, userId)) < 1) {
            throw new RuntimeException("일지하는 항목이 없습니다.");
        }

        ProdSearch prodSearch = new ProdSearch();
        prodSearch.setProdId(prodId);
        Prod prod = clfdProdService.select(prodSearch);
        clfdProdService.minusRcmdNo(prod);
        clfdProdService.update(prod);
    }
}
