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

import edu.prlab.tyler.iotgateway.gateway.pojo.auth.SensitiveUser;
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<SensitiveUser> registerNewUser(SensitiveUser user) {
        return Optional.ofNullable(user)
                .map(SensitiveUser::getAccount)
                .filter(account->!userRepository.existsByAccount(account))
                .map(account -> userRepository.save(user));
    }

    //TODO
    //需要增加解密確認
    public Optional<SensitiveUser> login(SensitiveUser user) {
        return Optional.ofNullable(user.getAccount())
                .map(account -> userRepository.findUserByAccount(account))
                .filter(sensitiveUser->sensitiveUser.getPassword().equals(user.getPassword()));
    }
}
