/**
 * Supplier model
 */

const { query, execute } = require('./baseModel');

async function createSupplier({ supplierCode, supplierName, telephone, address, email }) {
  await execute(
    'INSERT INTO Supplier (supplierCode, supplierName, telephone, address, email) VALUES (?, ?, ?, ?, ?)',
    [supplierCode, supplierName, telephone || null, address || null, email || null]
  );

  return getSupplierByCode(supplierCode);
}

async function getAllSuppliers() {
  return query('SELECT * FROM Supplier ORDER BY supplierCode ASC');
}

async function getSupplierByCode(supplierCode) {
  const rows = await query('SELECT * FROM Supplier WHERE supplierCode = ? LIMIT 1', [supplierCode]);
  return rows[0] || null;
}

async function updateSupplier({ supplierCode, supplierName, telephone, address, email }) {
  const supplier = await getSupplierByCode(supplierCode);
  if (!supplier) return null;

  await execute(
    `UPDATE Supplier
     SET supplierName = ?, telephone = ?, address = ?, email = ?
     WHERE supplierCode = ?`,
    [
      supplierName ?? supplier.supplierName,
      telephone ?? supplier.telephone,
      address ?? supplier.address,
      email ?? supplier.email,
      supplierCode
    ]
  );

  return getSupplierByCode(supplierCode);
}

module.exports = {
  createSupplier,
  getAllSuppliers,
  getSupplierByCode,
  updateSupplier
};

