package com.realnet.users.service;

import com.realnet.users.entity.User;
import com.realnet.users.model.UserProfileUpdateRequest;
import com.realnet.users.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class UserProfileService {

    @Autowired
    private UserRepository userRepository;

    public Optional<User> getUserProfile(Long userId) {
        return userRepository.findById(userId);
    }

    public User updateUserProfile(Long userId, UserProfileUpdateRequest updateRequest) {
        return userRepository.findById(userId).map(user -> {
            if (updateRequest.getEmail() != null && !updateRequest.getEmail().isEmpty()) {
                user.setEmail(updateRequest.getEmail());
            }
            if (updateRequest.getProfilePictureUrl() != null && !updateRequest.getProfilePictureUrl().isEmpty()) {
                user.setProfilePictureUrl(updateRequest.getProfilePictureUrl());
            }
            if (updateRequest.getStatus() != null && !updateRequest.getStatus().isEmpty()) {
                user.setStatus(updateRequest.getStatus());
            }
            user.setUpdatedAt(LocalDateTime.now());
            return userRepository.save(user);
        }).orElseThrow(() -> new RuntimeException("User not found with id " + userId));
    }

    public List<User> searchUsers(String query) {
        // This will search by username or email
        return userRepository.findByUsernameContainingIgnoreCaseOrEmailContainingIgnoreCase(query, query);
    }
}