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

const create = async (plan, callback) => {
  try {
    const db = await getDb();
    const {
      project_id, drawing_name,
      pipe_spec, area_number,
      spool_number, length
    } = plan;

    const [result] = await db.query(
      `INSERT INTO CuttingPlan
       (project_id, drawing_name, pipe_spec, area_number, spool_number, length)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [project_id, drawing_name, pipe_spec, area_number, spool_number, length]
    );

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

const getAll = async (callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT * FROM CuttingPlan ORDER BY cutting_plan_id DESC`
    );
    callback(null, rows);
  } catch (err) {
    callback(new Error(err.message || String(err)));
  }
};

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

const update = async (plan, callback) => {
  try {
    const db = await getDb();
    const {
      cutting_plan_id, project_id, drawing_name,
      pipe_spec, area_number, spool_number, length
    } = plan;

    const [result] = await db.query(
      `UPDATE CuttingPlan
       SET project_id    = ?,
           drawing_name  = ?,
           pipe_spec     = ?,
           area_number   = ?,
           spool_number  = ?,
           length        = ?
       WHERE cutting_plan_id = ?`,
      [project_id, drawing_name, pipe_spec, area_number, spool_number, length, cutting_plan_id]
    );

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

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

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