const { getPool } = require('./userModel');

// ===== 업체(공급업체) =====

async function findAll({ search, is_active } = {}) {
  const db = getPool();
  let sql = 'SELECT * FROM vendors WHERE 1=1';
  const params = [];
  if (is_active !== undefined) { sql += ' AND is_active = ?'; params.push(is_active); }
  if (search) { sql += ' AND (vendor_name LIKE ? OR business_number LIKE ? OR contact_name LIKE ?)'; params.push(`%${search}%`, `%${search}%`, `%${search}%`); }
  sql += ' ORDER BY vendor_name';
  const [rows] = await db.query(sql, params);
  return rows;
}

async function findById(id) {
  const db = getPool();
  const [rows] = await db.query('SELECT * FROM vendors WHERE vendor_id = ?', [id]);
  return rows[0] || null;
}

async function create(data) {
  const db = getPool();
  const [result] = await db.query(
    `INSERT INTO vendors (vendor_name, business_number, representative, contact_name, contact_phone, address, bank_name, bank_account, notes)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
    [data.vendor_name, data.business_number || null, data.representative || null,
     data.contact_name || null, data.contact_phone || null, data.address || null,
     data.bank_name || null, data.bank_account || null, data.notes || null]
  );
  return findById(result.insertId);
}

async function update(id, data) {
  const db = getPool();
  const fields = [];
  const values = [];
  if (data.vendor_name !== undefined) { fields.push('vendor_name = ?'); values.push(data.vendor_name); }
  if (data.business_number !== undefined) { fields.push('business_number = ?'); values.push(data.business_number || null); }
  if (data.representative !== undefined) { fields.push('representative = ?'); values.push(data.representative || null); }
  if (data.contact_name !== undefined) { fields.push('contact_name = ?'); values.push(data.contact_name || null); }
  if (data.contact_phone !== undefined) { fields.push('contact_phone = ?'); values.push(data.contact_phone || null); }
  if (data.address !== undefined) { fields.push('address = ?'); values.push(data.address || null); }
  if (data.bank_name !== undefined) { fields.push('bank_name = ?'); values.push(data.bank_name || null); }
  if (data.bank_account !== undefined) { fields.push('bank_account = ?'); values.push(data.bank_account || null); }
  if (data.notes !== undefined) { fields.push('notes = ?'); values.push(data.notes || null); }
  if (data.is_active !== undefined) { fields.push('is_active = ?'); values.push(data.is_active); }
  if (fields.length === 0) return findById(id);
  values.push(id);
  await db.query(`UPDATE vendors SET ${fields.join(', ')} WHERE vendor_id = ?`, values);
  return findById(id);
}

async function deactivate(id) {
  const db = getPool();
  await db.query('UPDATE vendors SET is_active = FALSE WHERE vendor_id = ?', [id]);
}

module.exports = { findAll, findById, create, update, deactivate };
