import { db } from '$lib/db/db.js';
/** 
* Return of functions that change change DB, either 'success' or 'failure' with explanation
* @typedef {Object} ChangeDBResult
* @property {string} [error]
* @property {string} [success]
* @property {string} [id]
*/

/**
* @function addUserToDB Adds user to the db
* @param {string} email
* @param {string} passwordHash
* @param {boolean} isAdmin
* @returns {ChangeDBResult} 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 {ChangeDBResult} 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` }
}

/**
* @function addPosterToDB
* @param {any} image
* @param {string} content
* @returns {ChangeDBResult} return
*/
export const addPosterToDB = (image, content) => {

  const id = crypto.randomUUID(); // Create random ID for Poster
  console.log("New id is: ", id);

  const createdAt = Date.now().toString;

  if (!image) { // Return error if mandatory info is missing
    return {
      error: "Image missing"
    }
  }

  const addPoster = db.prepare(`INSERT INTO Posters(id,createdAt,image,content) VALUES ($id,$createdAt,$image,$content);`);
  const result = addPoster.run({
    id: id,
    createdAt: createdAt,
    image: image,
    content: content
  });

  if (result.changes === 1) {
    return {
      success: `Poster added to DB with id ${id}`,
      id
    }
  }
  return { // Default return just in case
    error: `Could not save poster '${id}' to DB. Something went wrong`
  }
}

export const getAllPostersFromDB = () => {
  const getPosters = db.prepare(`SELECT * FROM Posters;`);
  const result = getPosters.all();
  return result;
}
