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 News findNewsById(int newsId){
        return newsRepository.findNewsById(newsId);
    }
    //Find news By Employee Id
    public List<News> findByEmployeeId(int employeeId){
        return newsRepository.findByEmployeeId(employeeId);
    }
    // FInd 4 latest news by câtlogiId
    public List<News> findLatestNews(int catalogiId){
        return newsRepository.getLatestNews(catalogiId);
    }
    // Find 4 latest news
    public List<News> findAllLatestNews(){
        return newsRepository.getAllLatestNews();
    }
    // Find news By Catalogi
    public List<News> findByCatalogiId(int catalogiId){
        return newsRepository.findByCatalogiId(catalogiId);
    }


    public News findNewsByIdAndEmployeeId(int id, int employeeId){
        return newsRepository.findByIdAndEmployeeId(id,employeeId);
    }

    public News findNewsByIdAndAndCatalogiId(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 newsId,int employeeId){
        News news = newsRepository.findByIdAndEmployeeId(newsId,employeeId);
        if(news == null){
            throw new ResourceNotFoundException("News" ,"newsId",newsId);
        }
        newsRepository.delete(news);
        return "ok";

    }

}
