const { User, OTP } = require("../models");
const { BadRequestError } = require("../utils/errors");
const { sendEmail } = require("../utils/helpers");


class OTPService {
  async generateOTP(userId, type, ip, device) {
    const user = await User.findOne({
      where: {
        id: userId
      }
    })
    const otp = await OTP.createOTP({
      userId,
      type,
      identifier: user.email,
      expiryMinutes: 20,
      ip,
      device
    })
    sendEmail({
      "type": "2fa",
      "to": user.email,
      "data": {
        otp: String(otp.code)
      },
      "subject": "Your 2fa code"
    })
    return {
      message: `Otp send to ${user.email}`,
      otp
    }
  }

  async verifyOTP(userId, type, code) {

    // Find latest valid OTP
    const otp = await OTP.findValidOTP(userId, type, code);

    if (!otp) {
      throw new Error('Invalid or expired OTP');
    }

    // Mark as used
    await otp.verify(code);

    return {
      status: true,
    };
  }

  async invalidatePrevious(userId, type) {
    await OTP.invalidatePrevious(userId, type)
  }
}

module.exports = new OTPService()