const db = require("../db/db");

const register = async (
  User_Name,
  hash,
  Email,
  Contact_No
) => {
  const sql = `INSERT INTO Users (User_Name,Password, Email,Contact_No) VALUES (?, ?, ? , ?)`;
  return new Promise((resolve, reject) => {
    db.query(
      sql,
      [User_Name, hash, Email, Contact_No],
      (err, results) => {
        if (err) {
          reject(err);
        } else {
          resolve(results);
        }
      }
    );
  });
};

const checkUser = (identifier, isEmail) => {
  const sql = isEmail
    ? `SELECT * FROM users WHERE Email = ?`
    : `SELECT * FROM users WHERE Contact_No = ?`;

  return new Promise((resolve, reject) => {
    db.query(sql, [identifier], (err, results) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
};

const getUserbyId = (idUser) => {
  const sql = `SELECT User_Name FROM users WHERE idUser = ?`;
  return new Promise((resolve, reject) => {
    db.query(sql, [idUser], (err, results) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
};

module.exports = {
  register,
  checkUser,
  getUserbyId,
};
