package com.project.whatsappchatbot.service;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.project.whatsappchatbot.constant.UserExists;
import com.project.whatsappchatbot.model.Customer;
import com.project.whatsappchatbot.repository.AccountRepository;
import com.project.whatsappchatbot.repository.CustomerRepository;

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Refill;

@Service
public class AccountService {

    private final int RATE_LIMIT;
	
    private final int RATE_LIMIT_TIME;
	
	private final Bucket bucket;
	@Autowired
	private AccountRepository accountRepository;

	@Autowired
    private CustomerRepository customerRepository;

	@Autowired
	public AccountService(@Value("${user.exists.rate.limit:200}") int rateLimit,
			@Value("${user.exists.rate.limit.with.time:1}") int rateLimitTime, AccountRepository accountRepository) {
		this.RATE_LIMIT = rateLimit;
		this.RATE_LIMIT_TIME = rateLimitTime;
		this.accountRepository = accountRepository;

		Bandwidth limit = Bandwidth.classic(RATE_LIMIT, Refill.greedy(RATE_LIMIT, Duration.ofMinutes(RATE_LIMIT_TIME)));
		this.bucket = Bucket.builder().addLimit(limit).build();
	}

    public String checkIfUserExists(final String phone) {
        if (bucket.tryConsume(1)) {
            return customerRepository.existsByPhone(phone) ? UserExists.USER_EXISTS : UserExists.USER_NOT_EXISTS;
        }
        return UserExists.USER_EXISTS_RATE_LIMIT;

    }
}