package com.realnet.user_profile.service;

import com.realnet.exceptions.UserNotFoundException;
import com.realnet.user_profile.entity.UserProfileDTO;
import com.realnet.users.entity.User;
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.Optional;

@Service
public class UserProfileService {

    @Autowired
    private UserRepository userRepository;

    public UserProfileDTO getUserProfileById(Long id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new UserNotFoundException("User not found with id: " + id));
        return mapUserToUserProfileDTO(user);
    }

    public UserProfileDTO updateUserProfile(Long id, UserProfileDTO userProfileDTO) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new UserNotFoundException("User not found with id: " + id));

        // Update user fields from DTO
        user.setUsername(userProfileDTO.getUsername());
        user.setEmail(userProfileDTO.getEmail());
        // Assuming firstName and lastName are not directly in User entity, 
        // if they were, you would update them here.
        // For now, only updating fields that exist in the User entity.
        // If profilePictureUrl or status are part of UserProfileDTO, update them here.

        user.setUpdatedAt(LocalDateTime.now());
        User updatedUser = userRepository.save(user);
        return mapUserToUserProfileDTO(updatedUser);
    }

    private UserProfileDTO mapUserToUserProfileDTO(User user) {
        UserProfileDTO dto = new UserProfileDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setEmail(user.getEmail());
        // Map other fields if they exist in User entity and UserProfileDTO
        // For example, if User had getFirstName() and getLastName()
        // dto.setFirstName(user.getFirstName());
        // dto.setLastName(user.getLastName());
        return dto;
    }
}
