import dotenv from 'dotenv';
import { purchaseOrderModel } from '../../database/schemas/inventory/purchaseorder.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('Purchase Orders');
logger.level = process.env.LOG_LEVEL;

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

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

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

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

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

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

export const getPurchaseOrderRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: purchaseOrderModel,
    id,
    populate: ['vendor'],
  });
  if (result?.error) {
    logger.warn(`Purchase Order not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived purchase order with ID: ${id}`);
  res.send(result);
};

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

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

  const updateData = {
    updatedAt: new Date(),
    vendor: req.body.vendor,
  };
  // Create audit log before updating
  const result = await editObject({
    model: purchaseOrderModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newPurchaseOrderRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    vendor: req.body.vendor,
  };
  const result = await newObject({
    model: purchaseOrderModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No purchase order created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

export const getPurchaseOrderStatsRouteHandler = async (req, res) => {
  const result = await getModelStats({ model: purchaseOrderModel });
  if (result?.error) {
    logger.error('Error fetching purchase order stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Purchase order stats:', result);
  res.send(result);
};

export const getPurchaseOrderHistoryRouteHandler = async (req, res) => {
  const from = req.query.from;
  const to = req.query.to;
  const result = await getModelHistory({ model: purchaseOrderModel, from, to });
  if (result?.error) {
    logger.error('Error fetching purchase order history:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Purchase order history:', result);
  res.send(result);
};
