// controllers/workerController.js
const workerModel = require('../models/workerModel');

// 1. 작업자 생성
exports.createWorker = async (req, res) => {
  try {
    const workerData = req.body;
    const lastID = await new Promise((resolve, reject) => {
      workerModel.create(workerData, (err, id) => {
        if (err) reject(err);
        else resolve(id);
      });
    });
    res.json({ success: true, worker_id: lastID });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 2. 전체 작업자 조회
exports.getAllWorkers = async (req, res) => {
  try {
    const rows = await new Promise((resolve, reject) => {
      workerModel.getAll((err, data) => {
        if (err) reject(err);
        else resolve(data);
      });
    });
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 3. 단일 작업자 조회
exports.getWorkerById = async (req, res) => {
  try {
    const id = parseInt(req.params.worker_id, 10);
    const row = await new Promise((resolve, reject) => {
      workerModel.getById(id, (err, data) => {
        if (err) reject(err);
        else resolve(data);
      });
    });
    if (!row) return res.status(404).json({ error: 'Worker not found' });
    res.json(row);
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 4. 작업자 수정
exports.updateWorker = async (req, res) => {
  try {
    const id = parseInt(req.params.worker_id, 10);
    const workerData = { ...req.body, worker_id: id };
    const changes = await new Promise((resolve, reject) => {
      workerModel.update(workerData, (err, affected) => {
        if (err) reject(err);
        else resolve(affected);
      });
    });
    if (changes === 0) return res.status(404).json({ error: 'Worker not found or no change' });
    res.json({ success: true, changes });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

// 5. 작업자 삭제
exports.removeWorker = async (req, res) => {
  try {
    const id = parseInt(req.params.worker_id, 10);
    const changes = await new Promise((resolve, reject) => {
      workerModel.remove(id, (err, affected) => {
        if (err) reject(err);
        else resolve(affected);
      });
    });
    if (changes === 0) return res.status(404).json({ error: 'Worker not found' });
    res.json({ success: true, changes });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};