/*
 * 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.question;

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 QuestionService {
    private final QuestionRepository questionRepository;
    private final Logger logger = LoggerFactory.getLogger(QuestionService.class);

    @Autowired
    public QuestionService(QuestionRepository questionRepository) {
        this.questionRepository = questionRepository;
    }

    public List<Question> getAllQuestions() {
        try {
            return questionRepository.findAll();
        } catch (Exception ex) {
            logger.error("Error while fetching all questions", ex);
            throw new ServiceException("Error while fetching all questions", ex);
        }
    }

    public Optional<Question> getQuestionById(Integer id) {
        if (!questionRepository.existsById(id)) {
            logger.error("Error while fetching question by ID: {}", id);
            throw new ServiceException("Error while fetching question by ID: " + id);
        }
        return questionRepository.findById(id);

    }

    public Question addQuestion(Question question) {
        try {
            return questionRepository.save(question);
        } catch (Exception ex) {
            logger.error("Error while adding question: {}", question, ex);
            throw new ServiceException("Error while adding question: " + question, ex);
        }
    }

    public Question updateQuestion(Integer id, Question question) {
        if (!questionRepository.existsById(id)) {
            logger.error("Error while updating question with ID {}: {}", id, question);
            throw new ServiceException("Error while updating question with ID " + id + ": " + question);
        }
        question.setId(id);
        return questionRepository.save(question);
    }

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