const Tools = require('../models/toolsModel');

// 1. 전체 도구 조회
exports.getAll = async (req, res) => {
  try {
    const rows = await new Promise((resolve, reject) => {
      Tools.getAllTools((err, data) => err ? reject(err) : resolve(data));
    });
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 2. 단일 도구 조회
exports.getById = async (req, res) => {
  try {
    const id = parseInt(req.params.id, 10);
    const row = await new Promise((resolve, reject) => {
      Tools.getToolById(id, (err, data) => err ? reject(err) : resolve(data));
    });
    if (!row) return res.status(404).json({ error: 'Tool not found' });
    res.json(row);
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 3. 도구 생성
exports.create = async (req, res) => {
  try {
    const insertId = await new Promise((resolve, reject) => {
      Tools.createTool(req.body, (err, resultId) => {
        if (err) return reject(err);
        resolve(resultId);
      });
    });
    res.status(201).json({ success: true, id: insertId });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 4. 도구 수정
exports.update = async (req, res) => {
  try {
    const id = parseInt(req.params.id, 10);
    const changedRows = await new Promise((resolve, reject) => {
      Tools.updateTool(id, req.body, (err, affectedRows) => {
        if (err) return reject(err);
        resolve(affectedRows);
      });
    });
    if (changedRows === 0) return res.status(404).json({ error: 'Tool not found or no change' });
    res.json({ success: true, changes: changedRows });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 5. 도구 삭제
exports.delete = async (req, res) => {
  try {
    const id = parseInt(req.params.id, 10);
    const deletedRows = await new Promise((resolve, reject) => {
      Tools.deleteTool(id, (err, affectedRows) => {
        if (err) return reject(err);
        resolve(affectedRows);
      });
    });
    if (deletedRows === 0) return res.status(404).json({ error: 'Tool not found' });
    res.status(204).send();
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};