import { config } from '../config';
import { prisma } from '../config/database';
import { redis } from '../config/redis';

export function generateOtp(): string {
  return Math.floor(100000 + Math.random() * 900000).toString();
}

export async function checkOtpRateLimit(phone: string): Promise<boolean> {
  if (!redis) return true;

  const key = `otp:ratelimit:${phone}`;
  const count = await redis.incr(key);

  if (count === 1) {
    await redis.expire(key, 3600);
  }

  return count <= config.otp.maxAttemptsPerHour;
}

export async function storeOtp(phone: string, otp: string): Promise<void> {
  const expiresAt = new Date(Date.now() + config.otp.expirySeconds * 1000);

  const user = await prisma.user.findUnique({ where: { phone } });

  await prisma.otpRecord.create({
    data: {
      phone,
      otp,
      expiresAt,
      userId: user?.id,
    },
  });
}

export async function verifyOtp(phone: string, otp: string): Promise<boolean> {
  const record = await prisma.otpRecord.findFirst({
    where: {
      phone,
      verified: false,
      expiresAt: { gt: new Date() },
    },
    orderBy: { createdAt: 'desc' },
  });

  if (!record) {
    return false;
  }

  await prisma.otpRecord.update({
    where: { id: record.id },
    data: { attempts: record.attempts + 1 },
  });

  if (record.attempts >= 3) {
    return false;
  }

  if (record.otp !== otp) {
    return false;
  }

  await prisma.otpRecord.update({
    where: { id: record.id },
    data: { verified: true },
  });

  return true;
}

export async function sendOtpSms(phone: string, otp: string): Promise<void> {
  if (config.nodeEnv === 'development') {
    console.log(`[DEV] OTP for ${phone}: ${otp}`);
    return;
  }

  console.log(`Sending OTP to ${phone} via ${config.sms.provider}`);
}
