// controllers/equipmentListController.js
const equipmentListModel = require('../models/equipmentListModel');

// 1. 등록
exports.createEquipment = async (req, res) => {
  try {
    const equipmentData = req.body;
    const id = await new Promise((resolve, reject) => {
      equipmentListModel.create(equipmentData, (err, insertId) =>
        err ? reject(err) : resolve(insertId)
      );
    });
    res.json({ success: true, equipment_id: id });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

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

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

// 4. 수정
exports.updateEquipment = async (req, res) => {
  try {
    const id = parseInt(req.params.equipment_id, 10);
    const data = { ...req.body, equipment_id: id };
    const changes = await new Promise((resolve, reject) => {
      equipmentListModel.update(data, (err, affectedRows) =>
        err ? reject(err) : resolve(affectedRows)
      );
    });
    if (changes === 0) return res.status(404).json({ error: 'No changes or not found' });
    res.json({ success: true, changes });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 5. 삭제
exports.removeEquipment = async (req, res) => {
  try {
    const id = parseInt(req.params.equipment_id, 10);
    const changes = await new Promise((resolve, reject) => {
      equipmentListModel.remove(id, (err, affectedRows) =>
        err ? reject(err) : resolve(affectedRows)
      );
    });
    if (changes === 0) return res.status(404).json({ error: 'Equipment not found' });
    res.json({ success: true, changes });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};