import { otpRecord } from "../../config/otpRecord.config";

export const otpStore: Map<string, otpRecord> = new Map();

// Function to generate an OTP and store it in the otpStore
export const generateOtp = () => {
  return Math.floor(100000 + Math.random() * 900000).toString();
};
export const storeOtp = (email: string, otp: string): void => {
  const expiresAt = Date.now() + 5 * 60 * 1000;
  otpStore.set(email, { otp, expiresAt });
};

//verify otp from memory
export const verifyOtp = (email: string, otp: string): boolean => {
  const record = otpStore.get(email);
  if (!record) {
    return false;
  }

  if (record.expiresAt < Date.now()) {
    otpStore.delete(email);
    return false;
  }

  return record.otp === otp;
};

//clean up the expired otp
export const cleanUpOtp = (): void => {
  const now = Date.now();
  otpStore.forEach((record, email) => {
    if (record.expiresAt < now) {
      otpStore.delete(email);
    }
  });
};
