package cz.muni.fi.pa165.core.user;

import cz.muni.fi.pa165.core.common.DomainService;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;

@Service
public class UserService extends DomainService<User> {

	@Getter
	private final UserRepository repository;

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


	@Transactional(readOnly = true)
	public User findByUsername(String username) {
		return getRepository()
				.findByUsername(username)
				.filter(entity -> entity.getDeletedAt() == null)
				.orElse(null);
	}

	@Transactional(readOnly = true)
	public Double getConsumption(String userId,
								 String houseId,
								 Instant startTime,
								 Instant endTime) {
		return repository.getStatisticsData(userId, houseId, startTime, endTime);
	}

	// TODO: use salt
	@Transactional(readOnly = true)
	public boolean loginCheck(String userId, String password) {
		return getRepository()
				.findByIdAndPassword(userId, password)
				.filter(entity -> entity.getDeletedAt() == null)
				.isPresent();
	}
}
