import dotenv from 'dotenv';
import { shipmentModel } from '../../database/schemas/inventory/shipment.schema.js';
import log4js from 'log4js';
import mongoose from 'mongoose';
import {
  deleteObject,
  listObjects,
  getObject,
  editObject,
  newObject,
  listObjectsByProperties,
  getModelStats,
  getModelHistory,
} from '../../database/database.js';
dotenv.config();

const logger = log4js.getLogger('Shipments');
logger.level = process.env.LOG_LEVEL;

export const listShipmentsRouteHandler = async (
  req,
  res,
  page = 1,
  limit = 25,
  property = '',
  filter = {},
  search = '',
  sort = '',
  order = 'ascend'
) => {
  const result = await listObjects({
    model: shipmentModel,
    page,
    limit,
    property,
    filter,
    search,
    sort,
    order,
    populate: ['purchaseOrder', 'vendor', 'courierService'],
  });

  if (result?.error) {
    logger.error('Error listing shipments.');
    res.status(result.code).send(result);
    return;
  }

  logger.debug(`List of shipments (Page ${page}, Limit ${limit}). Count: ${result.length}`);
  res.send(result);
};

export const listShipmentsByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {},
  masterFilter = {}
) => {
  const result = await listObjectsByProperties({
    model: shipmentModel,
    properties,
    filter,
    populate: ['purchaseOrder', 'vendor', 'courierService'],
    masterFilter,
  });

  if (result?.error) {
    logger.error('Error listing shipments.');
    res.status(result.code).send(result);
    return;
  }

  logger.debug(`List of shipments. Count: ${result.length}`);
  res.send(result);
};

export const getShipmentRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: shipmentModel,
    id,
    populate: ['purchaseOrder', 'vendor', 'courierService', 'items.item', 'items.taxRate'],
  });
  if (result?.error) {
    logger.warn(`Shipment not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived shipment with ID: ${id}`);
  res.send(result);
};

export const editShipmentRouteHandler = async (req, res) => {
  // Get ID from params
  const id = new mongoose.Types.ObjectId(req.params.id);

  logger.trace(`Shipment with ID: ${id}`);

  const updateData = {
    updatedAt: new Date(),
    purchaseOrder: req.body.purchaseOrder,
    vendor: req.body.vendor,
    courierService: req.body.courierService,
    trackingNumber: req.body.trackingNumber,
    shippedDate: req.body.shippedDate,
    expectedDeliveryDate: req.body.expectedDeliveryDate,
    actualDeliveryDate: req.body.actualDeliveryDate,
    state: req.body.state,
    notes: req.body.notes,
  };
  // Create audit log before updating
  const result = await editObject({
    model: shipmentModel,
    id,
    updateData,
    user: req.user,
  });

  if (result.error) {
    logger.error('Error editing shipment:', result.error);
    res.status(result).send(result);
    return;
  }

  logger.debug(`Edited shipment with ID: ${id}`);

  res.send(result);
};

export const newShipmentRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    purchaseOrder: req.body.purchaseOrder,
    vendor: req.body.vendor,
    courierService: req.body.courierService,
    trackingNumber: req.body.trackingNumber,
    items: req.body.items,
    cost: req.body.cost,
    shippedDate: req.body.shippedDate,
    expectedDeliveryDate: req.body.expectedDeliveryDate,
    actualDeliveryDate: req.body.actualDeliveryDate,
    state: req.body.state,
    notes: req.body.notes,
  };
  const result = await newObject({
    model: shipmentModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No shipment created:', result.error);
    return res.status(result.code).send(result);
  }

  logger.debug(`New shipment with ID: ${result._id}`);

  res.send(result);
};

export const deleteShipmentRouteHandler = async (req, res) => {
  // Get ID from params
  const id = new mongoose.Types.ObjectId(req.params.id);

  logger.trace(`Shipment with ID: ${id}`);

  const result = await deleteObject({
    model: shipmentModel,
    id,
    user: req.user,
  });
  if (result.error) {
    logger.error('No shipment deleted:', result.error);
    return res.status(result.code).send(result);
  }

  logger.debug(`Deleted shipment with ID: ${result._id}`);

  res.send(result);
};

export const getShipmentStatsRouteHandler = async (req, res) => {
  const result = await getModelStats({ model: shipmentModel });
  if (result?.error) {
    logger.error('Error fetching shipment stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Shipment stats:', result);
  res.send(result);
};

export const getShipmentHistoryRouteHandler = async (req, res) => {
  const from = req.query.from;
  const to = req.query.to;
  const result = await getModelHistory({ model: shipmentModel, from, to });
  if (result?.error) {
    logger.error('Error fetching shipment history:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Shipment history:', result);
  res.send(result);
};
