package org.ros.chatto.service;

import org.ros.chatto.model.UserToken;
import org.ros.chatto.repository.TokenRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Transactional
@Slf4j
@CacheConfig(cacheNames = "userTokenCache")
@RequiredArgsConstructor
public class UserTokenService {
	private final TokenRepository tokenRepository;

	@Transactional(readOnly = true)
	@Cacheable(value = "userTokenCache", key = "#userName", unless = "#result == null")
	public UserToken getTokenByUserName(String userName) {
		return tokenRepository.findByUserName(userName);
	}

	@Transactional(readOnly = true)
	@Cacheable(value = "userTokenCache", key = "#tokenString", unless = "#result == null")
	public UserToken getTokenByTokenString(String tokenString) {
		return tokenRepository.findByToken(tokenString);
	}

	public void saveToken(UserToken userToken) {
		log.trace("Saving auth token");
		tokenRepository.save(userToken);
	}

	public void deleteToken(String userName) {
		log.trace("Deleting token for {}", userName);
		tokenRepository.deleteByUserName(userName);
	}

	public void deleteToken(UserToken userToken) {
		log.trace("Deleting token for {}", userToken);
		tokenRepository.delete(userToken);
	}
}
