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

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

async function getById(req, res) {
  try {
    const vendor = await vendorModel.findById(req.params.id);
    if (!vendor) return res.status(404).json({ success: false, error: '업체를 찾을 수 없습니다' });
    res.json({ success: true, data: vendor });
  } catch (err) {
    console.error('Vendor get error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function create(req, res) {
  try {
    const { vendor_name } = req.body;
    if (!vendor_name || !vendor_name.trim()) {
      return res.status(400).json({ success: false, error: '업체명은 필수입니다' });
    }
    const vendor = await vendorModel.create(req.body);
    res.status(201).json({ success: true, data: vendor });
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ success: false, error: '이미 등록된 업체입니다' });
    }
    console.error('Vendor create error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

async function update(req, res) {
  try {
    const vendor = await vendorModel.update(req.params.id, req.body);
    if (!vendor) return res.status(404).json({ success: false, error: '업체를 찾을 수 없습니다' });
    res.json({ success: true, data: vendor });
  } catch (err) {
    console.error('Vendor update error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
}

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

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