/**
 * Shipment model
 */

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

async function createShipment({ shipmentNumber, shipmentDate, shipmentStatus, destination, supplierCode }) {
  await execute(
    'INSERT INTO Shipment (shipmentNumber, shipmentDate, shipmentStatus, destination, supplierCode) VALUES (?, ?, ?, ?, ?)',
    [shipmentNumber, shipmentDate, shipmentStatus, destination, supplierCode]
  );

  return getShipmentByNumber(shipmentNumber);
}

async function getAllShipments() {
  return query(
    `SELECT s.*, sp.supplierName
     FROM Shipment s
     LEFT JOIN Supplier sp ON sp.supplierCode = s.supplierCode
     ORDER BY s.shipmentDate DESC, s.shipmentNumber ASC`
  );
}

async function getShipmentByNumber(shipmentNumber) {
  const rows = await query(
    `SELECT s.*, sp.supplierName
     FROM Shipment s
     LEFT JOIN Supplier sp ON sp.supplierCode = s.supplierCode
     WHERE s.shipmentNumber = ?
     LIMIT 1`,
    [shipmentNumber]
  );
  return rows[0] || null;
}

async function updateShipment({ shipmentNumber, shipmentDate, shipmentStatus, destination, supplierCode }) {
  const current = await getShipmentByNumber(shipmentNumber);
  if (!current) return null;

  await execute(
    `UPDATE Shipment
     SET shipmentDate = ?, shipmentStatus = ?, destination = ?, supplierCode = ?
     WHERE shipmentNumber = ?`,
    [shipmentDate ?? current.shipmentDate, shipmentStatus ?? current.shipmentStatus, destination ?? current.destination, supplierCode ?? current.supplierCode, shipmentNumber]
  );

  return getShipmentByNumber(shipmentNumber);
}

async function deleteShipment(shipmentNumber) {
  const current = await getShipmentByNumber(shipmentNumber);
  if (!current) return false;
  await execute('DELETE FROM Shipment WHERE shipmentNumber = ?', [shipmentNumber]);
  return true;
}

module.exports = { createShipment, getAllShipments, getShipmentByNumber, updateShipment, deleteShipment };

