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

// 1. 프로젝트 생성
exports.createProject = async (req, res) => {
  try {
    const projectData = req.body;
    const id = await new Promise((resolve, reject) => {
      projectModel.create(projectData, (err, lastID) => (err ? reject(err) : resolve(lastID)));
    });
    res.json({ success: true, project_id: id });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

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

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

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

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