// controllers/factoryInfoController.js
const factoryInfoModel = require('../models/factoryInfoModel');

// 1. 공장 정보 생성
exports.createFactoryInfo = async (req, res) => {
  try {
    const factoryData = req.body;
    const id = await new Promise((resolve, reject) => {
      factoryInfoModel.create(factoryData, (err, insertId) =>
        err ? reject(err) : resolve(insertId)
      );
    });
    res.json({ success: true, factory_id: id });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

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

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

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

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