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

// ===== 소모품 마스터 =====

async function findAll({ category, search, is_active } = {}) {
  const db = getPool();
  let sql = 'SELECT * FROM consumable_items WHERE 1=1';
  const params = [];
  if (is_active !== undefined) { sql += ' AND is_active = ?'; params.push(is_active); }
  if (category) { sql += ' AND category = ?'; params.push(category); }
  if (search) { sql += ' AND (item_name LIKE ? OR maker LIKE ? OR spec LIKE ?)'; params.push(`%${search}%`, `%${search}%`, `%${search}%`); }
  sql += ' ORDER BY category, item_name';
  const [rows] = await db.query(sql, params);
  return rows;
}

async function findById(id) {
  const db = getPool();
  const [rows] = await db.query('SELECT * FROM consumable_items WHERE item_id = ?', [id]);
  return rows[0] || null;
}

async function create(data) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO consumable_items (item_name, spec, maker, category, base_price, unit, photo_path)
     VALUES (?, ?, ?, ?, ?, ?, ?)`,
    [data.item_name, data.spec || null, data.maker || null, data.category,
     data.base_price || 0, data.unit || 'EA', data.photo_path || null]
  );
  return findById(result.insertId);
}

async function update(id, data) {
  const db = getPool();
  const fields = [];
  const values = [];
  if (data.item_name !== undefined) { fields.push('item_name = ?'); values.push(data.item_name); }
  if (data.spec !== undefined) { fields.push('spec = ?'); values.push(data.spec || null); }
  if (data.maker !== undefined) { fields.push('maker = ?'); values.push(data.maker || null); }
  if (data.category !== undefined) { fields.push('category = ?'); values.push(data.category); }
  if (data.base_price !== undefined) { fields.push('base_price = ?'); values.push(data.base_price); }
  if (data.unit !== undefined) { fields.push('unit = ?'); values.push(data.unit || 'EA'); }
  if (data.photo_path !== undefined) { fields.push('photo_path = ?'); values.push(data.photo_path || null); }
  if (data.is_active !== undefined) { fields.push('is_active = ?'); values.push(data.is_active); }
  if (fields.length === 0) return findById(id);
  values.push(id);
  await db.query(`UPDATE consumable_items SET ${fields.join(', ')} WHERE item_id = ?`, values);
  return findById(id);
}

async function deactivate(id) {
  const db = getPool();
  await db.query('UPDATE consumable_items SET is_active = FALSE WHERE item_id = ?', [id]);
}

module.exports = { findAll, findById, create, update, deactivate };
