/**
 * Task Controller
 *
 * 공정(work_types) + 작업(tasks) CRUD
 */

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

/* ===== Work Types ===== */

async function getWorkTypes(req, res, next) {
  try {
    const data = await taskModel.getWorkTypes();
    res.json({ success: true, data });
  } catch (err) { next(err); }
}

async function createWorkType(req, res, next) {
  try {
    const { name } = req.body;
    if (!name) return res.status(400).json({ success: false, error: '공정명은 필수입니다' });
    const data = await taskModel.createWorkType(req.body);
    res.status(201).json({ success: true, data });
  } catch (err) { next(err); }
}

async function updateWorkType(req, res, next) {
  try {
    const data = await taskModel.updateWorkType(parseInt(req.params.id), req.body);
    if (!data) return res.status(404).json({ success: false, error: '공정을 찾을 수 없습니다' });
    res.json({ success: true, data });
  } catch (err) { next(err); }
}

async function deleteWorkType(req, res, next) {
  try {
    await taskModel.deleteWorkType(parseInt(req.params.id));
    res.json({ success: true, message: '공정이 삭제되었습니다' });
  } catch (err) { next(err); }
}

/* ===== Tasks ===== */

async function getTasks(req, res, next) {
  try {
    const workTypeId = req.query.work_type_id ? parseInt(req.query.work_type_id) : null;
    const data = await taskModel.getTasks(workTypeId);
    res.json({ success: true, data });
  } catch (err) { next(err); }
}

async function getActiveTasks(req, res, next) {
  try {
    const data = await taskModel.getActiveTasks();
    res.json({ success: true, data });
  } catch (err) { next(err); }
}

async function getTaskById(req, res, next) {
  try {
    const data = await taskModel.getTaskById(parseInt(req.params.id));
    if (!data) return res.status(404).json({ success: false, error: '작업을 찾을 수 없습니다' });
    res.json({ success: true, data });
  } catch (err) { next(err); }
}

async function createTask(req, res, next) {
  try {
    const { task_name } = req.body;
    if (!task_name) return res.status(400).json({ success: false, error: '작업명은 필수입니다' });
    const data = await taskModel.createTask(req.body);
    res.status(201).json({ success: true, data });
  } catch (err) { next(err); }
}

async function updateTask(req, res, next) {
  try {
    const data = await taskModel.updateTask(parseInt(req.params.id), req.body);
    if (!data) return res.status(404).json({ success: false, error: '작업을 찾을 수 없습니다' });
    res.json({ success: true, data });
  } catch (err) { next(err); }
}

async function deleteTask(req, res, next) {
  try {
    await taskModel.deleteTask(parseInt(req.params.id));
    res.json({ success: true, message: '작업이 삭제되었습니다' });
  } catch (err) { next(err); }
}

module.exports = {
  getWorkTypes, createWorkType, updateWorkType, deleteWorkType,
  getTasks, getActiveTasks, getTaskById, createTask, updateTask, deleteTask
};
