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

const create = async (project, callback) => {
  try {
    const db = await getDb();
    const {
      job_no, project_name,
      contract_date, due_date,
      delivery_method, site, pm
    } = project;
  
    const [result] = await db.query(
      `INSERT INTO Projects
       (job_no, project_name, contract_date, due_date, delivery_method, site, pm)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [job_no, project_name, contract_date, due_date, delivery_method, site, pm]
    );

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

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

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

const update = async (project, callback) => {
  try {
    const db = await getDb();
    const {
      project_id, job_no, project_name,
      contract_date, due_date,
      delivery_method, site, pm
    } = project;

    const [result] = await db.query(
      `UPDATE Projects
       SET job_no         = ?,
           project_name   = ?,
           contract_date  = ?,
           due_date       = ?,
           delivery_method= ?,
           site           = ?,
           pm             = ?
       WHERE project_id = ?`,
      [job_no, project_name, contract_date, due_date, delivery_method, site, pm, project_id]
    );

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

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

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