package de.szut.casino.user;

import de.szut.casino.user.dto.CreateUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Optional;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserEntity createUser(CreateUserDto createUserDto) {
        if (userRepository.existsByUsername(createUserDto.getUsername())) {
            throw new IllegalArgumentException("Username is already taken");
        }

        if (userRepository.existsByEmail(createUserDto.getEmail())) {
            throw new IllegalArgumentException("Email is already in use");
        }
        
        UserEntity user = new UserEntity(
            createUserDto.getEmail(),
            createUserDto.getUsername(),
            passwordEncoder.encode(createUserDto.getPassword()),
            BigDecimal.valueOf(10)  // Starting balance
        );
        
        return userRepository.save(user);
    }

    public Optional<UserEntity> getCurrentUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();

        return userRepository.findByUsername(username);
    }
}
