// controllers/projectMemberController.js

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

/**
 * สร้างความสัมพันธ์ (Create)
 */
exports.createProjectMember = async (req, res) => {
  try {
    // ข้อมูลจาก client เช่น { user_id, project_id, role_in_project }
    const { user_id, project_id, role_in_project } = req.body;

    const newPM = await ProjectMember.create({
      user_id,
      project_id,
      role_in_project
    });

    return res.status(201).json({
      message: 'ProjectMember created successfully',
      projectMember: newPM
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

/**
 * ดึงข้อมูลสมาชิกโครงการทั้งหมด (Read All)
 */
exports.getAllProjectMembers = async (req, res) => {
  try {
    const pms = await ProjectMember.findAll();
    return res.status(200).json(pms);
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

/**
 * ดึงข้อมูลสมาชิกโครงการตาม id (Read One)
 */
exports.getProjectMemberById = async (req, res) => {
  try {
    const { id } = req.params; // pm_id
    const pm = await ProjectMember.findByPk(id);

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

/**
 * อัปเดตข้อมูลสมาชิกโครงการ (Update)
 */
exports.updateProjectMember = async (req, res) => {
  try {
    const { id } = req.params;
    const { user_id, project_id, role_in_project } = req.body;

    const [rowsUpdated] = await ProjectMember.update({
      user_id,
      project_id,
      role_in_project
    }, {
      where: { pm_id: id },
    });

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

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

/**
 * ลบสมาชิกโครงการ (Delete)
 */
exports.deleteProjectMember = async (req, res) => {
  try {
    const { id } = req.params;
    const rowsDeleted = await ProjectMember.destroy({ where: { pm_id: id } });

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

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