/**
 * Supplier controller
 */

const {
  createSupplier,
  getAllSuppliers,
  getSupplierByCode,
  updateSupplier
} = require('../models/supplier.model');

async function create(req, res) {
  const supplier = await createSupplier(req.body);
  return res.status(201).json(supplier);
}

async function getAll(_req, res) {
  const suppliers = await getAllSuppliers();
  return res.json({ data: suppliers });
}

async function getOne(req, res) {
  const supplier = await getSupplierByCode(req.params.supplierCode);
  if (!supplier) return res.status(404).json({ error: 'NOT_FOUND', message: 'Supplier not found' });
  return res.json(supplier);
}

async function update(req, res) {
  const updated = await updateSupplier({ supplierCode: req.params.supplierCode, ...req.body });
  if (!updated) return res.status(404).json({ error: 'NOT_FOUND', message: 'Supplier not found' });
  return res.json(updated);
}

module.exports = { create, getAll, getOne, update };

