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

// 1. 생성
const create = async (task, callback) => {
  try {
    const db = await getDb();
    const { category, subcategory, task_name, description } = task;

    const [result] = await db.query(
      `INSERT INTO Tasks (category, subcategory, task_name, description)
       VALUES (?, ?, ?, ?)`,
      [category, subcategory, task_name, description]
    );

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

// 2. 전체 조회
const getAll = async (callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT * FROM Tasks ORDER BY task_id DESC`
    );
    callback(null, rows);
  } catch (err) {
    callback(err);
  }
};

// 3. 단일 조회
const getById = async (task_id, callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT * FROM Tasks WHERE task_id = ?`,
      [task_id]
    );
    callback(null, rows[0]);
  } catch (err) {
    callback(err);
  }
};

// 4. 수정
const update = async (task, callback) => {
  try {
    const db = await getDb();
    const { task_id, category, subcategory, task_name, description } = task;

    const [result] = await db.query(
      `UPDATE Tasks
       SET category     = ?,
           subcategory  = ?,
           task_name    = ?,
           description  = ?
       WHERE task_id    = ?`,
      [category, subcategory, task_name, description, task_id]
    );

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

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

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