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

const create = async (equipment, callback) => {
  try {
    const db = await getDb();
    const {
      factory_id, equipment_name,
      model, status, purchase_date, description
    } = equipment;

    const [result] = await db.query(
      `INSERT INTO EquipmentList
       (factory_id, equipment_name, model, status, purchase_date, description)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [factory_id, equipment_name, model, status, purchase_date, description]
    );

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

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

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

const update = async (equipment, callback) => {
  try {
    const db = await getDb();
    const {
      equipment_id, factory_id, equipment_name,
      model, status, purchase_date, description
    } = equipment;

    const [result] = await db.query(
      `UPDATE EquipmentList
       SET factory_id    = ?,
           equipment_name = ?,
           model          = ?,
           status         = ?,
           purchase_date  = ?,
           description    = ?
       WHERE equipment_id = ?`,
      [factory_id, equipment_name, model, status, purchase_date, description, equipment_id]
    );

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

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

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