import dotenv from 'dotenv';
import { orderItemModel } from '../../database/schemas/inventory/orderitem.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('Order Items');
logger.level = process.env.LOG_LEVEL;

export const listOrderItemsRouteHandler = async (
  req,
  res,
  page = 1,
  limit = 25,
  property = '',
  filter = {},
  search = '',
  sort = '',
  order = 'ascend'
) => {
  const result = await listObjects({
    model: orderItemModel,
    page,
    limit,
    property,
    filter,
    search,
    sort,
    order,
    populate: [
      {
        path: 'order',
      },
      {
        path: 'taxRate',
        strictPopulate: false,
      },
      {
        path: 'item',
        populate: { path: 'costTaxRate', strictPopulate: false },
      },
      {
        path: 'item',
        populate: { path: 'priceTaxRate', strictPopulate: false },
      },
    ],
  });

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

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

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

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

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

export const getOrderItemRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: orderItemModel,
    id,
    populate: [
      {
        path: 'order',
      },
      {
        path: 'taxRate',
        strictPopulate: false,
      },
      {
        path: 'item',
        populate: { path: 'costTaxRate', strictPopulate: false },
        strictPopulate: false,
      },
      {
        path: 'item',
        populate: { path: 'priceTaxRate', strictPopulate: false },
        strictPopulate: false,
      },
    ],
  });
  if (result?.error) {
    logger.warn(`Order Item not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived order item with ID: ${id}`);
  res.send(result);
};

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

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

  const updateData = {
    updatedAt: new Date(),
    itemType: req.body.itemType,
    item: req.body.item,
    orderType: req.body.orderType,
    order: req.body.order,
    syncAmount: req.body.syncAmount,
    itemAmount: req.body.itemAmount,
    quantity: req.body.quantity,
    totalAmount: req.body.totalAmount,
    taxRate: req.body.taxRate,
    totalAmountWithTax: req.body.totalAmountWithTax,
  };
  // Create audit log before updating
  const result = await editObject({
    model: orderItemModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newOrderItemRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    purchaseOrder: req.body.purchaseOrder,
    state: { type: 'draft' },
    itemType: req.body.itemType,
    item: req.body.item,
    orderType: req.body.orderType,
    order: req.body.order,
    syncAmount: req.body.syncAmount,
    itemAmount: req.body.itemAmount,
    quantity: req.body.quantity,
    totalAmount: req.body.totalAmount,
    taxRate: req.body.taxRate,
    totalAmountWithTax: req.body.totalAmountWithTax,
  };
  const result = await newObject({
    model: orderItemModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No order item created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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