// controllers/projectController.js
const Project = require('../models/Project');

/**
 * สร้างโครงการใหม่ (Create)
 */
exports.createProject = async (req, res) => {
  try {
    // ข้อมูลที่ต้องการจาก body เช่น: { project_name, project_desc, start_date, end_date }
    const { project_name, project_desc, start_date, end_date } = req.body;

    const newProject = await Project.create({
      project_name,
      project_desc,
      start_date,
      end_date
    });

    return res.status(201).json({
      message: 'Project created successfully',
      project: newProject
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ error: error.message });
  }
};

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

/**
 * ดึงข้อมูลโครงการจาก ID (Read One)
 */
exports.getProjectById = async (req, res) => {
  try {
    const { id } = req.params;
    const project = await Project.findByPk(id);

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

/**
 * อัปเดตข้อมูลโครงการ (Update)
 */
exports.updateProject = async (req, res) => {
  try {
    const { id } = req.params;
    const { project_name, project_desc, start_date, end_date } = req.body;

    const [rowsUpdated] = await Project.update(
      {
        project_name,
        project_desc,
        start_date,
        end_date
      },
      {
        where: { project_id: id },
      }
    );

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

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

/**
 * ลบโครงการ (Delete)
 */
exports.deleteProject = async (req, res) => {
  try {
    const { id } = req.params;
    const rowsDeleted = await Project.destroy({ where: { project_id: id } });

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

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