/**
 * Worker Controller
 *
 * 작업자 CRUD
 */

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

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

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

async function create(req, res, next) {
  try {
    const { worker_name } = req.body;
    if (!worker_name) {
      return res.status(400).json({ success: false, error: '작업자 이름은 필수입니다' });
    }
    const worker = await workerModel.create(req.body);
    res.status(201).json({ success: true, data: worker });
  } catch (err) {
    next(err);
  }
}

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

async function remove(req, res, next) {
  try {
    const id = parseInt(req.params.id);
    await workerModel.deactivate(id);
    res.json({ success: true, message: '작업자가 비활성화되었습니다' });
  } catch (err) {
    next(err);
  }
}

module.exports = { getAll, getById, create, update, remove };
