package kr.co.zioinfo.web.service;

import kr.co.zioinfo.web.model.News;
import kr.co.zioinfo.web.repository.NewsRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class NewsService {
    private final NewsRepository repo;

    public Page<News> findAll(String category, Pageable pageable) {
        if (category != null && !category.isBlank()) {
            return repo.findByCategoryAndVisibleTrue(category, pageable);
        }
        return repo.findByVisibleTrue(pageable);
    }

    public Optional<News> findById(Long id) {
        return repo.findById(id).map(n -> {
            n.setViewCount(n.getViewCount() + 1);
            return repo.save(n);
        });
    }
}
