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

import com.Sae301.ApiMathsEduc.player.*;
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 PlayerService {
    private final PlayerRepository playerRepository;
    private final Logger logger = LoggerFactory.getLogger(PlayerService.class);

    @Autowired
    public PlayerService(PlayerRepository playerRepository) {
        this.playerRepository = playerRepository;
    }

    public List<Player> getAllPlayers() {
        try {
            return playerRepository.findAll();
        } catch (Exception ex) {
            logger.error("Error while fetching all players", ex);
            throw new ServiceException("Error while fetching all players", ex);
        }
    }

    public Optional<Player> getPlayerById(Integer id) {
        if (!playerRepository.existsById(id)) {
            logger.error("Error while fetching player by ID: {}", id);
            throw new ServiceException("Error while fetching player by ID: " + id);
        }
        return playerRepository.findById(id);

    }

    public Player addPlayer(Player player) {
        try {
            return playerRepository.save(player);
        } catch (Exception ex) {
            logger.error("Error while adding player: {}", player, ex);
            throw new ServiceException("Error while adding player: " + player, ex);
        }
    }

    public Player updatePlayer(Integer id, Player player) {
        if (!playerRepository.existsById(id)) {
            logger.error("Error while updating player with ID {}: {}", id, player);
            throw new ServiceException("Error while updating player with ID " + id + ": " + player);
        }
        player.setId(id);
        return playerRepository.save(player);
    }

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