package com.example.demo.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class OtpStore {

    private final Map<String, String> otpMap = new ConcurrentHashMap<>();
    private final Map<String, Long> expiryMap = new ConcurrentHashMap<>();
    private final Map<String, Long> lastSentMap = new ConcurrentHashMap<>();

    private static final long EXPIRY_MS = 5 * 60 * 1000;      // 5 minutes
    private static final long RESEND_COOLDOWN_MS = 60 * 1000; // 1 minute


    public void save(String email, String otp) {
        otpMap.put(email, otp);
        expiryMap.put(email, System.currentTimeMillis() + EXPIRY_MS);
        lastSentMap.put(email, System.currentTimeMillis());
    }


    public boolean validate(String email, String otp) {
        Long expiry = expiryMap.get(email);

        if (expiry == null || System.currentTimeMillis() > expiry) {
            clear(email);
            return false;
        }

        return otp.equals(otpMap.get(email));
    }

    public boolean canResend(String email) {
        long now = System.currentTimeMillis();
        long lastSent = lastSentMap.getOrDefault(email, 0L);

        return (now - lastSent) >= RESEND_COOLDOWN_MS;
    }

    public void clear(String email) {
        otpMap.remove(email);
        expiryMap.remove(email);
        lastSentMap.remove(email);
    }


    @Scheduled(fixedRate = 120000)
    public void clearExpired() {
        long now = System.currentTimeMillis();

        expiryMap.entrySet().removeIf(entry -> {
            if (now > entry.getValue()) {
                String email = entry.getKey();
                otpMap.remove(email);
                lastSentMap.remove(email);
                return true;
            }
            return false;
        });
    }
}