package edu.prlab.tyler.iotgateway.gateway.services;

import edu.prlab.tyler.iotgateway.gateway.pojo.auth.User;
import edu.prlab.tyler.iotgateway.gateway.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {
    private UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    //TODO
    //需要增加加密機制
    public Optional<User> registerNewUser(User user) {
        return Optional.ofNullable(user)
                .map(User::getUsername)
                .filter(username->!userRepository.existsByUsername(username))
                .map(username -> userRepository.save(user));
    }

    //TODO
    //需要增加解密確認
    public Optional<User> login(User user) {
        return Optional.ofNullable(user.getUsername())
                .map(username -> userRepository.findUserByUsername(username))
                .filter(sensitiveUser->sensitiveUser.getPassword().equals(user.getPassword()));
    }
}
