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

// 1. 전체 도구 조회
const getAll = async () => {
  const db = await getDb();
  const [rows] = await db.query('SELECT id, name, location, stock, status, factory_id, map_x, map_y, map_zone, map_note FROM Tools');
  return rows;
};

// 2. 단일 도구 조회
const getById = async (id) => {
  const db = await getDb();
  const [rows] = await db.query('SELECT id, name, location, stock, status, factory_id, map_x, map_y, map_zone, map_note FROM Tools WHERE id = ?', [id]);
  return rows[0];
};

// 3. 도구 생성
const create = async (tool) => {
  const db = await getDb();
  const { name, location, stock, status, factory_id, map_x, map_y, map_zone, map_note } = tool;

  const [result] = await db.query(
    `INSERT INTO Tools
     (name, location, stock, status, factory_id, map_x, map_y, map_zone, map_note)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
    [name, location, stock, status, factory_id, map_x, map_y, map_zone, map_note]
  );

  return result.insertId;
};

// 4. 도구 수정
const update = async (id, tool) => {
  const db = await getDb();
  const { name, location, stock, status, factory_id, map_x, map_y, map_zone, map_note } = tool;

  const [result] = await db.query(
    `UPDATE Tools
     SET name       = ?,
         location   = ?,
         stock      = ?,
         status     = ?,
         factory_id = ?,
         map_x      = ?,
         map_y      = ?,
         map_zone   = ?,
         map_note   = ?
     WHERE id = ?`,
    [name, location, stock, status, factory_id, map_x, map_y, map_zone, map_note, id]
  );

  return result.affectedRows;
};

// 5. 도구 삭제
const remove = async (id) => {
  const db = await getDb();
  const [result] = await db.query('DELETE FROM Tools WHERE id = ?', [id]);
  return result.affectedRows;
};

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