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

// 1. 작업자 생성
const create = async (worker, callback) => {
  try {
    const db = await getDb();
    const { worker_name, join_date, job_type, salary, annual_leave, status } = worker;

    const [result] = await db.query(
      `INSERT INTO Workers 
       (worker_name, join_date, job_type, salary, annual_leave, status)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [worker_name, join_date, job_type, salary, annual_leave, status]
    );

    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 Workers ORDER BY worker_id DESC`);
    callback(null, rows);
  } catch (err) {
    callback(err);
  }
};

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

// 4. 작업자 수정
const update = async (worker, callback) => {
  try {
    const db = await getDb();
    const { worker_id, worker_name, join_date, job_type, salary, annual_leave, status } = worker;

    const [result] = await db.query(
      `UPDATE Workers
       SET worker_name   = ?,
           join_date     = ?,
           job_type      = ?,
           salary        = ?,
           annual_leave  = ?,
           status        = ?
       WHERE worker_id = ?`,
      [worker_name, join_date, job_type, salary, annual_leave, status, worker_id]
    );

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

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

// ✅ 모듈 내보내기 (정상 구조)
module.exports = {
  create,
  getAll,
  getById,
  update,
  remove
};