const { pool } = require("../config/database/database.config");

async function addPerson(person) {
  // extract all the values from person
  let {
    firstName,
    lastName,
    middleName,
    maidenName,
    suffix,
    nickName,
    techAlumniChapter,
    classYear,
    gradYear,
    gradSemester,
    gender,
  } = person;

  // find the integer that represents the alumni chapter (for now do 2)
  techAlumniChapter = 2;

  console.log("In here now");

  try {
    console.log("Adding person: ", firstName);

    const query = `
      INSERT INTO people (firstName, lastName, middleName, maidenName, suffix, nickName, techAlumniChapter, classYear, gradYear, gradSemester, gender)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;

    const [results] = await pool.query(query, [
      firstName,
      lastName,
      middleName,
      maidenName,
      suffix,
      nickName,
      techAlumniChapter,
      classYear,
      gradYear,
      gradSemester,
      gender,
    ]);

    // return the new person's id
    return results.insertId;
  } catch (error) {
    console.error(error);
    return null;
  }
}

/*
Function to search for people by their first and last name, 
if multiple people with that name exist, they will all be returned. 
If no people are found, the function will return null.
*/
async function searchPeopleByName(firstName, lastName) {
  console.log("searching for people by name....");

  try {
    // SQL query to search for people by first and last name
    const query = `
      SELECT * FROM people
      WHERE firstName = ? AND lastName = ?
      `;

    // Execute the query and pass the first and last name as parameters
    const [results] = await pool.query(query, [firstName, lastName]);

    console.log("results found: ", results);

    // If no people are found, return null
    if (results.length === 0) {
      return null;
    }

    // return the people found
    return results;
  } catch (error) {
    console.error(error);
    return null;
  }
}

async function getPersonById() {}

async function deletePersonById() {}

module.exports = { addPerson, searchPeopleByName };