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

// CREATE
const create = async (type, callback) => {
  try {
    const db = await getDb();
    const [result] = await db.query(
      `INSERT INTO IssueTypes (category, subcategory) VALUES (?, ?)`,
      [type.category, type.subcategory]
    );
    callback(null, result.insertId);
  } catch (err) {
    callback(err);
  }
};

// READ ALL
const getAll = async (callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(`SELECT * FROM IssueTypes ORDER BY category, subcategory`);
    callback(null, rows);
  } catch (err) {
    callback(err);
  }
};

// UPDATE
const update = async (id, type, callback) => {
  try {
    const db = await getDb();
    const [result] = await db.query(
      `UPDATE IssueTypes SET category = ?, subcategory = ? WHERE id = ?`,
      [type.category, type.subcategory, id]
    );
    callback(null, result.affectedRows);
  } catch (err) {
    callback(err);
  }
};

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

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