import Redis from 'ioredis'
import dotenv from 'dotenv'
dotenv.config()

const redis = new Redis({
  host: process.env.REDIS_HOST,
  port: process.env.REDIS_PORT,
  connectTimeout: 10000, 
  maxRetriesPerRequest: null
})

redis.on('error', (err) => {
  // Log the error so you know it's happening, but don't crash
  console.error('Redis connection error:', err.code); 
})

// Optional: Log when connected successfully
redis.on('connect', () => {
  console.log('Connected to Redis successfully');
})

export async function saveOtp(email, otp) {
  const key = `otp:${email}`
  const ttl = parseInt(process.env.OTP_TTL_SECONDS || '300')
  await redis.setex(key, ttl, otp)
}

export async function verifyOtp(email, otp) {
  const key = `otp:${email}`
  const stored = await redis.get(key)
  if (!stored) return false
  return stored === otp
}

export async function removeOtp(email) {
  const key = `otp:${email}`
  await redis.del(key)
}

export default redis
