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

// 1. 생성
exports.createTask = async (req, res) => {
  try {
    const taskData = req.body;
    const lastID = await new Promise((resolve, reject) => {
      taskModel.create(taskData, (err, id) => (err ? reject(err) : resolve(id)));
    });
    res.json({ success: true, task_id: lastID });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

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

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

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

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