/**
 * Worker Model
 *
 * workers 테이블 CRUD (MariaDB)
 */

const { getPool } = require('./userModel');

async function getAll() {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT w.*, d.department_name
     FROM workers w
     LEFT JOIN departments d ON w.department_id = d.department_id
     ORDER BY w.worker_id DESC`
  );
  return rows;
}

async function getById(id) {
  const db = getPool();
  const [rows] = await db.query(
    `SELECT w.*, d.department_name
     FROM workers w
     LEFT JOIN departments d ON w.department_id = d.department_id
     WHERE w.worker_id = ?`,
    [id]
  );
  return rows[0] || null;
}

async function create({ worker_name, job_type, department_id, phone_number, hire_date, notes }) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO workers (worker_name, job_type, department_id, phone_number, hire_date, notes)
     VALUES (?, ?, ?, ?, ?, ?)`,
    [worker_name, job_type || null, department_id || null, phone_number || null, hire_date || null, notes || null]
  );
  return getById(result.insertId);
}

async function update(id, data) {
  const db = getPool();
  const fields = [];
  const values = [];

  if (data.worker_name !== undefined) { fields.push('worker_name = ?'); values.push(data.worker_name); }
  if (data.job_type !== undefined) { fields.push('job_type = ?'); values.push(data.job_type); }
  if (data.status !== undefined) { fields.push('status = ?'); values.push(data.status); }
  if (data.department_id !== undefined) { fields.push('department_id = ?'); values.push(data.department_id || null); }
  if (data.employment_status !== undefined) { fields.push('employment_status = ?'); values.push(data.employment_status); }
  if (data.phone_number !== undefined) { fields.push('phone_number = ?'); values.push(data.phone_number || null); }
  if (data.hire_date !== undefined) { fields.push('hire_date = ?'); values.push(data.hire_date || null); }
  if (data.notes !== undefined) { fields.push('notes = ?'); values.push(data.notes || null); }

  if (fields.length === 0) return getById(id);

  values.push(id);
  await db.query(
    `UPDATE workers SET ${fields.join(', ')} WHERE worker_id = ?`,
    values
  );
  return getById(id);
}

async function deactivate(id) {
  const db = getPool();
  await db.query(
    'UPDATE workers SET status = ? WHERE worker_id = ?',
    ['inactive', id]
  );
}

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