const consumableItemModel = require('../models/consumableItemModel');
const fs = require('fs');
const path = require('path');

async function list(req, res) {
  try {
    const { category, search, is_active } = req.query;
    const rows = await consumableItemModel.findAll({
      category,
      search,
      is_active: is_active !== undefined ? is_active === 'true' || is_active === '1' : undefined
    });
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('ConsumableItem list error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function getById(req, res) {
  try {
    const item = await consumableItemModel.findById(req.params.id);
    if (!item) return res.status(404).json({ success: false, error: '소모품을 찾을 수 없습니다' });
    res.json({ success: true, data: item });
  } catch (err) {
    console.error('ConsumableItem get error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function create(req, res) {
  try {
    const { item_name, category } = req.body;
    if (!item_name || !item_name.trim()) {
      return res.status(400).json({ success: false, error: '품명은 필수입니다' });
    }
    if (!category) {
      return res.status(400).json({ success: false, error: '분류는 필수입니다' });
    }
    const data = { ...req.body };
    if (req.file) {
      data.photo_path = '/uploads/consumables/' + req.file.filename;
    }
    const item = await consumableItemModel.create(data);
    res.status(201).json({ success: true, data: item });
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ success: false, error: '동일한 품명+메이커 조합이 이미 존재합니다' });
    }
    console.error('ConsumableItem create error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function update(req, res) {
  try {
    const existing = await consumableItemModel.findById(req.params.id);
    if (!existing) return res.status(404).json({ success: false, error: '소모품을 찾을 수 없습니다' });

    const data = { ...req.body };
    if (req.file) {
      data.photo_path = '/uploads/consumables/' + req.file.filename;
      // 기존 사진 삭제
      if (existing.photo_path) {
        const oldPath = path.join(__dirname, '..', existing.photo_path);
        fs.unlink(oldPath, () => {});
      }
    }
    const item = await consumableItemModel.update(req.params.id, data);
    res.json({ success: true, data: item });
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ success: false, error: '동일한 품명+메이커 조합이 이미 존재합니다' });
    }
    console.error('ConsumableItem update error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function deactivate(req, res) {
  try {
    await consumableItemModel.deactivate(req.params.id);
    res.json({ success: true, message: '비활성화 완료' });
  } catch (err) {
    console.error('ConsumableItem deactivate error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

module.exports = { list, getById, create, update, deactivate };
