// controllers/projectEquipmentController.js

const ProjectEquipment = require('../models/ProjectEquipment');

/**
 * สร้างข้อมูล ProjectEquipment ใหม่ (Create)
 */
exports.createProjectEquipment = async (req, res) => {
  try {
    // ข้อมูลจาก body เช่น { project_id, equipment_id, quantity_in_project }
    const { project_id, equipment_id, quantity_in_project } = req.body;

    const newPE = await ProjectEquipment.create({
      project_id,
      equipment_id,
      quantity_in_project
    });

    return res.status(201).json({
      message: 'ProjectEquipment created successfully',
      projectEquipment: newPE
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

/**
 * ดึงข้อมูล ProjectEquipments ทั้งหมด (Read All)
 */
exports.getAllProjectEquipments = async (req, res) => {
  try {
    const pes = await ProjectEquipment.findAll();
    return res.status(200).json(pes);
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

/**
 * ดึงข้อมูล ProjectEquipment ตาม pe_id (Read One)
 */
exports.getProjectEquipmentById = async (req, res) => {
  try {
    const { id } = req.params;  // pe_id
    const pe = await ProjectEquipment.findByPk(id);

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

/**
 * อัปเดตข้อมูล ProjectEquipment (Update)
 */
exports.updateProjectEquipment = async (req, res) => {
  try {
    const { id } = req.params;
    const { project_id, equipment_id, quantity_in_project } = req.body;

    const [rowsUpdated] = await ProjectEquipment.update(
      { project_id, equipment_id, quantity_in_project },
      { where: { pe_id: id } }
    );

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

    // ดึงข้อมูลใหม่หลังอัปเดต
    const updatedPE = await ProjectEquipment.findByPk(id);
    return res.status(200).json({
      message: 'ProjectEquipment updated successfully',
      projectEquipment: updatedPE
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

/**
 * ลบข้อมูล ProjectEquipment (Delete)
 */
exports.deleteProjectEquipment = async (req, res) => {
  try {
    const { id } = req.params;
    const rowsDeleted = await ProjectEquipment.destroy({ where: { pe_id: id } });

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

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