/**
 * Delivery model
 */

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

async function createDelivery({ deliveryCode, deliveryDate, quantityDelivered, deliveryStatus, shipmentNumber }) {
  await execute(
    'INSERT INTO Delivery (deliveryCode, deliveryDate, quantityDelivered, deliveryStatus, shipmentNumber) VALUES (?, ?, ?, ?, ?)',
    [deliveryCode, deliveryDate, quantityDelivered, deliveryStatus, shipmentNumber]
  );
  return getDeliveryByCode(deliveryCode);
}

async function getAllDeliveries() {
  return query(
    `SELECT d.*, s.shipmentNumber, s.destination
     FROM Delivery d
     LEFT JOIN Shipment s ON s.shipmentNumber = d.shipmentNumber
     ORDER BY d.deliveryDate DESC, d.deliveryCode ASC`
  );
}

async function getDeliveryByCode(deliveryCode) {
  const rows = await query(
    `SELECT d.*, s.shipmentNumber, s.destination
     FROM Delivery d
     LEFT JOIN Shipment s ON s.shipmentNumber = d.shipmentNumber
     WHERE d.deliveryCode = ?
     LIMIT 1`,
    [deliveryCode]
  );
  return rows[0] || null;
}

async function updateDelivery({ deliveryCode, deliveryDate, quantityDelivered, deliveryStatus, shipmentNumber }) {
  const current = await getDeliveryByCode(deliveryCode);
  if (!current) return null;

  await execute(
    `UPDATE Delivery
     SET deliveryDate = ?, quantityDelivered = ?, deliveryStatus = ?, shipmentNumber = ?
     WHERE deliveryCode = ?`,
    [deliveryDate ?? current.deliveryDate, quantityDelivered ?? current.quantityDelivered, deliveryStatus ?? current.deliveryStatus, shipmentNumber ?? current.shipmentNumber, deliveryCode]
  );

  return getDeliveryByCode(deliveryCode);
}

async function deleteDelivery(deliveryCode) {
  const current = await getDeliveryByCode(deliveryCode);
  if (!current) return false;
  await execute('DELETE FROM Delivery WHERE deliveryCode = ?', [deliveryCode]);
  return true;
}

module.exports = { createDelivery, getAllDeliveries, getDeliveryByCode, updateDelivery, deleteDelivery };

