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

import com.Sae301.ApiMathsEduc.lobby.*;
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 LobbyService {
    private final LobbyRepository lobbyRepository;
    private final Logger logger = LoggerFactory.getLogger(LobbyService.class);

    @Autowired
    public LobbyService(LobbyRepository lobbyRepository) {
        this.lobbyRepository = lobbyRepository;
    }

    public List<Lobby> getAllLobbies() {
        try {
            return lobbyRepository.findAll();
        } catch (Exception ex) {
            logger.error("Error while fetching all lobbies", ex);
            throw new ServiceException("Error while fetching all lobbies", ex);
        }
    }

    public Optional<Lobby> getLobbyById(Integer id) {
        if (!lobbyRepository.existsById(id)) {
            logger.error("Error while fetching lobby by ID: {}", id);
            throw new ServiceException("Error while fetching lobby by ID: " + id);
        }
        return lobbyRepository.findById(id);

    }

    public Lobby addLobby(Lobby lobby) {
        try {
            return lobbyRepository.save(lobby);
        } catch (Exception ex) {
            logger.error("Error while adding lobby: {}", lobby, ex);
            throw new ServiceException("Error while adding lobby: " + lobby, ex);
        }
    }

    public Lobby updateLobby(Integer id, Lobby lobby) {
        if (!lobbyRepository.existsById(id)) {
            logger.error("Error while updating lobby with ID {}: {}", id, lobby);
            throw new ServiceException("Error while updating lobby with ID " + id + ": " + lobby);
        }
        lobby.setId(id);
        return lobbyRepository.save(lobby);
    }

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