package com.itsol.quantrivanphong.access.homepage.business;

import com.itsol.quantrivanphong.access.homepage.repository.NewsRepository;
import com.itsol.quantrivanphong.exception.ResourceNotFoundException;
import com.itsol.quantrivanphong.model.News;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class NewsBusiness {
    @Autowired
    private NewsRepository newsRepository;

    public List<News> findAllNews(){
        return newsRepository.findAllNews();
    }
    // Find News By News Id
    public Optional<News> findById(int newsId){
        return newsRepository.findById(newsId);
    }
    //Find news By Employee Id
    public List<News> findByEmployeeId(int employeeId){
        return newsRepository.findByEmployeeId(employeeId);
    }
    // Find news By Catalogi
    public List<News> findByCatalogiId(int catalogiId){
        return newsRepository.findByCatalogiId(catalogiId);
    }


    public Optional<News> findByIdAndEmployeeId(int id, int employeeId){
        return newsRepository.findByIdAndEmployeeId(id,employeeId);
    }

    public Optional<News> findByIdAndAndCatalogiId(int id, int catalogiId){
        return newsRepository.findByIdAndAndCatalogiId(id,catalogiId);
    }

    public News save(News news){
        return newsRepository.save(news);
    }

    public News updateNews(int newsId, News newsDetails){
        News news = newsRepository.findNewsById(newsId);
        news.setTitle(newsDetails.getTitle());
        news.setContent(newsDetails.getContent());
        news.setSummary(newsDetails.getSummary());
        news.setThumbnail(newsDetails.getThumbnail());
        News updateNews = newsRepository.save(news);
        return updateNews;
    }

    public String deleteNews(int employeeId,int newsId){
        newsRepository.findByIdAndEmployeeId(employeeId,newsId).map(news ->{
            newsRepository.delete(news);
            return "ok";
        }).orElseThrow(() -> new ResourceNotFoundException("News" ,"newsId",newsId));
        return "Ok";
    }

}
