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

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 AnswerService {
    private final AnswerRepository answerRepository;
    private final Logger logger = LoggerFactory.getLogger(AnswerService.class);

    @Autowired
    public AnswerService(AnswerRepository answerRepository) {
        this.answerRepository = answerRepository;
    }

    public List<Answer> getAllAnswers() {
        try {
            return answerRepository.findAll();
        } catch (Exception ex) {
            logger.error("Error while fetching all answers", ex);
            throw new ServiceException("Error while fetching all answers", ex);
        }
    }

    public Optional<Answer> getAnswerById(Integer id) {
        if (!answerRepository.existsById(id)) {
            logger.error("Error while fetching answer by ID: {}", id);
            throw new ServiceException("Error while fetching answer by ID: " + id);
        }
        return answerRepository.findById(id);

    }

    public Answer addAnswer(Answer answer) {
        try {
            return answerRepository.save(answer);
        } catch (Exception ex) {
            logger.error("Error while adding answer: {}", answer, ex);
            throw new ServiceException("Error while adding answer: " + answer, ex);
        }
    }

    public Answer updateAnswer(Integer id, Answer answer) {
        if (!answerRepository.existsById(id)) {
            logger.error("Error while updating answer with ID {}: {}", id, answer);
            throw new ServiceException("Error while updating answer with ID " + id + ": " + answer);
        }
        answer.setId(id);
        return answerRepository.save(answer);
    }

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