/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.Sae301.ApiMathsEduc.chapter;

import java.util.List;
import java.util.Optional;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author Utilisateur
 */
@Service
public class ChapterService {
    private final ChapterRepository chapterRepository;
    private final Logger logger = LoggerFactory.getLogger(ChapterService.class);

    @Autowired
    public ChapterService(ChapterRepository chapterRepository) {
        this.chapterRepository = chapterRepository;
    }

    public List<Chapter> getAllChapters() {
        try {
            return chapterRepository.findAll();
        } catch (Exception ex) {
            logger.error("Error while fetching all chapters", ex);
            throw new ServiceException("Error while fetching all chapters", ex);
        }
    }

    public Optional<Chapter> getChapterById(Integer id) {
        if (!chapterRepository.existsById(id)) {
            logger.error("Error while fetching chapter by ID: {}", id);
            throw new ServiceException("Error while fetching chapter by ID: " + id);
        }
        return chapterRepository.findById(id);

    }

    public Chapter addChapter(Chapter chapter) {
        try {
            return chapterRepository.save(chapter);
        } catch (Exception ex) {
            logger.error("Error while adding chapter: {}", chapter, ex);
            throw new ServiceException("Error while adding chapter: " + chapter, ex);
        }
    }

    public Chapter updateChapter(Integer id, Chapter chapter) {
        if (!chapterRepository.existsById(id)) {
            logger.error("Error while updating chapter with ID {}: {}", id, chapter);
            throw new ServiceException("Error while updating chapter with ID " + id + ": " + chapter);
        }
        chapter.setId(id);
        return chapterRepository.save(chapter);
    }

    public void deleteChapter(Integer id) {
        if (!chapterRepository.existsById(id)) {
            logger.error("Error while deleting chapter with ID: {}", id);
            throw new ServiceException("Error while deleting chapter with ID: " + id);
        }
        chapterRepository.deleteById(id);
    }
}