const ConsumableCategoryModel = require('../models/consumableCategoryModel');
const logger = require('../utils/logger');

const ConsumableCategoryController = {
  getAll: async (req, res) => {
    try {
      const activeOnly = req.query.all !== '1';
      const rows = await ConsumableCategoryModel.getAll(activeOnly);
      res.json({ success: true, data: rows });
    } catch (err) {
      logger.error('ConsumableCategory getAll error:', err);
      res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
    }
  },

  create: async (req, res) => {
    try {
      const { category_code, category_name, icon, color_bg, color_fg, sort_order } = req.body;
      if (!category_code || !category_name) {
        return res.status(400).json({ success: false, message: '코드와 이름을 입력해주세요.' });
      }
      const cat = await ConsumableCategoryModel.create({
        categoryCode: category_code, categoryName: category_name,
        icon, colorBg: color_bg, colorFg: color_fg, sortOrder: sort_order
      });
      res.status(201).json({ success: true, data: cat, message: '카테고리가 추가되었습니다.' });
    } catch (err) {
      if (err.code === 'ER_DUP_ENTRY') {
        return res.status(400).json({ success: false, message: '이미 존재하는 코드입니다.' });
      }
      logger.error('ConsumableCategory create error:', err);
      res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
    }
  },

  update: async (req, res) => {
    try {
      const { category_name, icon, color_bg, color_fg, sort_order } = req.body;
      const cat = await ConsumableCategoryModel.update(req.params.id, {
        categoryName: category_name, icon, colorBg: color_bg, colorFg: color_fg, sortOrder: sort_order
      });
      if (!cat) return res.status(404).json({ success: false, message: '카테고리를 찾을 수 없습니다.' });
      res.json({ success: true, data: cat, message: '카테고리가 수정되었습니다.' });
    } catch (err) {
      logger.error('ConsumableCategory update error:', err);
      res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
    }
  },

  deactivate: async (req, res) => {
    try {
      const cat = await ConsumableCategoryModel.deactivate(req.params.id);
      if (!cat) return res.status(404).json({ success: false, message: '카테고리를 찾을 수 없습니다.' });
      res.json({ success: true, data: cat, message: '카테고리가 비활성화되었습니다.' });
    } catch (err) {
      logger.error('ConsumableCategory deactivate error:', err);
      res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
    }
  }
};

module.exports = ConsumableCategoryController;
