import DB from "../config/database/db";
import { ResultSetHeader, RowDataPacket } from "mysql2";

const otpDB: any = {};

type paramType = { mobile: string; otp?: string; status?: number };

otpDB.create = async ({ mobile, otp }: paramType) => {
  const query = "Insert into Otps (mobile, otp) values (?, ?)";
  const data = [mobile, otp];
  await DB.query<ResultSetHeader>(query, data);
  return true;
};

otpDB.getByMobile = async ({ mobile }: paramType) => {
  mobile = mobile.toString().substring(mobile.length - 10);
  const query =
    "Select * from Otps where mobile = ? and createdAt > DATE_ADD(now(), INTERVAL -10 MINUTE) order by id desc limit 1";
  const data = [mobile];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows[0];
  else return false;
};

otpDB.updateStatus = async ({ status, otp, mobile }: paramType) => {
  const query = "Update Otps set status = ? where otp = ? and mobile = ?";
  const data = [status, otp, mobile];
  await DB.execute<ResultSetHeader[]>(query, data);
  return true;
};

export default otpDB;
