import { db } from '$lib/db/db';

/** 
* Return of functions that change change DB, either 'success' or 'failure' with explanation
* @typedef {Object} DBActionResult
* @property {string} [error]
* @property {string} [success]
*/

/**
* @function addUserToDB Adds user to the db
* @param {string} email
* @param {string} passwordHash
* @param {boolean} isAdmin
* @returns {DBActionResult} return
*/
export const addUserToDB = (email, passwordHash, isAdmin) => {
  if (!email || !passwordHash || !isAdmin) {
    return {
      error: "Either email, password or isAdmin are missing"
    };
  }
  const addUser = db.prepare(`INSERT INTO Users(email,password,isAdmin) VALUES(?,?,?);`)
  const result = addUser.run(email, passwordHash, isAdmin);
  if (result.changes === 1) {
    return {
      success: `User '${email}' added to DB`
    }
  }
  return { error: `Could not add user '${email}' to DB`, };
}

/** Removes user from db
* @param {string} email
* @returns {DBActionResult} return
*/
export const delUserFromDB = (email) => {
  if (!email) {
    return {
      error: "Email not provided"
    }
  }
  const delUser = db.prepare(`DELETE FROM Users WHERE email=${email};`);
  const result = delUser.run();
  if (result.changes === 1) {
    return {
      success: `User '${email}' removed successfully`
    }
  }
  return { error: `Could not remove user '${email}' from DB` }
}

