// controllers/equipmentController.js
const Equipment = require('../models/Equipment');

/**
 * สร้างอุปกรณ์ใหม่ (Create)
 */
exports.createEquipment = async (req, res) => {
  try {
    // ข้อมูลที่จะรับจาก client ตัวอย่าง req.body = { equipment_name, description, quantity_total, location }
    const { equipment_name, description, quantity_total, location } = req.body;

    const newEquipment = await Equipment.create({
      equipment_name,
      description,
      quantity_total,
      location
    });

    return res.status(201).json({
      message: 'Equipment created successfully',
      equipment: newEquipment
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

/**
 * ดึงข้อมูลอุปกรณ์ทั้งหมด (Read All)
 */
exports.getAllEquipment = async (req, res) => {
  try {
    const equipments = await Equipment.findAll();
    return res.status(200).json(equipments);
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

/**
 * ดึงข้อมูลอุปกรณ์เฉพาะตัว (Read One)
 */
exports.getEquipmentById = async (req, res) => {
  try {
    const { id } = req.params; // equipment_id
    const equipment = await Equipment.findByPk(id);

    if (!equipment) {
      return res.status(404).json({ error: 'Equipment not found' });
    }
    return res.status(200).json(equipment);
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

/**
 * อัปเดตข้อมูลอุปกรณ์ (Update)
 */
exports.updateEquipment = async (req, res) => {
  try {
    const { id } = req.params;
    const { equipment_name, description, quantity_total, location } = req.body;

    const [rowsUpdated] = await Equipment.update(
      {
        equipment_name,
        description,
        quantity_total,
        location
      },
      {
        where: { equipment_id: id },
      }
    );

    if (!rowsUpdated) {
      return res.status(404).json({ error: 'Equipment not found or no changes' });
    }

    // หากต้องการส่งข้อมูลใหม่ที่เพิ่งอัปเดตกลับไป
    const updatedEquipment = await Equipment.findByPk(id);
    return res.status(200).json({
      message: 'Equipment updated successfully',
      equipment: updatedEquipment
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

/**
 * ลบอุปกรณ์ (Delete)
 */
exports.deleteEquipment = async (req, res) => {
  try {
    const { id } = req.params;
    const rowsDeleted = await Equipment.destroy({ where: { equipment_id: id } });

    if (!rowsDeleted) {
      return res.status(404).json({ error: 'Equipment not found' });
    }

    return res.status(200).json({ message: 'Equipment deleted successfully' });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};
