import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private ProfileRepository profileRepository;
// ✅ Create User
public User saveUser(User user) {
return userRepository.save(user);
}
// ✅ Get All Users
public List<User> getAllUsers() {
return userRepository.findAll();
}
// ✅ Get User by id
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
// ✅ Update User
public User updateUser(User user) {
return userRepository.save(user);
}
// ✅ Delete User By id
public String deleteUser(Long id) {
userRepository.deleteById(id);
return "User deleted!";
}
// ✅ Create User connect with existing profile
public User createUserWithExistingProfile(Long profileId, User user) {
if (profileId != null) {
Optional<Profile> existingProfile = profileRepository.findById(profileId);
existingProfile.ifPresent(user::setProfile);
}
return userRepository.save(user);
}
// ✅ Update User connect with existing profile
public User updateExistingUserProfile(Long profileId, Long userId) {
if (profileId != null && userId != null) {
Optional<Profile> existingProfile = profileRepository.findById(profileId);
Optional<User> existingUser = userRepository.findById(userId);
if (existingUser.isPresent() && existingProfile.isPresent()) {
User user = existingUser.get();
user.setProfile(existingProfile.get());
return userRepository.save(user);
}
}
return null;
}
// ✅ Update profile connected with user
public User updateUserProfileName(Long userId, String newProfileName) {
Optional<User> existingUser = userRepository.findById(userId);
if (existingUser.isPresent()) {
User user = existingUser.get();
Profile profile = user.getProfile();
if (profile != null) {
profile.setBio(newProfileName); // Update profile name (bio)
profileRepository.save(profile); // Save updated profile
return user;
} else {
throw new RuntimeException("Profile not found for User ID: " + userId);
}
} else {
throw new RuntimeException("User not found with ID: " + userId);
}
}
// ✅ Delete profile connected with user set null in profile_id column
public User removeUserProfile(Long userId) {
Optional<User> existingUser = userRepository.findById(userId);
if (existingUser.isPresent()) {
User user = existingUser.get();
Profile profile = user.getProfile();
if (profile != null) {
user.setProfile(null); // Remove profile from user
userRepository.save(user); // Save updated user (profile detached)
return user;
} else {
throw new RuntimeException("Profile not found for User ID: " + userId);
}
} else {
throw new RuntimeException("User not found with ID: " + userId);
}
}
}