const { getDb } = require('../dbPool');

const create = async (processData, callback) => {
  try {
    const db = await getDb();
    const {
      project_id, process_name,
      process_start, process_end,
      planned_worker_count, process_description, note
    } = processData;

    const [result] = await db.query(
      `INSERT INTO Processes
       (project_id, process_name, process_start, process_end,
        planned_worker_count, process_description, note)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [project_id, process_name, process_start, process_end,
       planned_worker_count, process_description, note]
    );

    callback(null, result.insertId);
  } catch (err) {
    callback(err);
  }
};

const getAll = async (callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT * FROM Processes ORDER BY process_id DESC`
    );
    callback(null, rows);
  } catch (err) {
    callback(err);
  }
};

const getById = async (process_id, callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT * FROM Processes WHERE process_id = ?`,
      [process_id]
    );
    callback(null, rows[0]);
  } catch (err) {
    callback(err);
  }
};

const update = async (processData, callback) => {
  try {
    const db = await getDb();
    const {
      process_id, project_id,
      process_name, process_start, process_end,
      planned_worker_count, process_description, note
    } = processData;

    const [result] = await db.query(
      `UPDATE Processes
       SET project_id            = ?,
           process_name         = ?,
           process_start        = ?,
           process_end          = ?,
           planned_worker_count = ?,
           process_description  = ?,
           note                 = ?
       WHERE process_id = ?`,
      [project_id, process_name, process_start, process_end,
       planned_worker_count, process_description, note, process_id]
    );

    callback(null, result.affectedRows);
  } catch (err) {
    callback(new Error(err.message || String(err)));
  }
};

const remove = async (process_id, callback) => {
  try {
    const db = await getDb();
    const [result] = await db.query(
      `DELETE FROM Processes WHERE process_id = ?`,
      [process_id]
    );
    callback(null, result.affectedRows);
  } catch (err) {
    callback(err);
  }
};

module.exports = {
  create,
  getAll,
  getById,
  update,
  remove
};