import dotenv from 'dotenv';
import { partStockModel } from '../../database/schemas/inventory/partstock.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('Part Stocks');
logger.level = process.env.LOG_LEVEL;

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

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

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

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

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

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

export const getPartStockRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: partStockModel,
    id,
    populate: [{ path: 'part' }],
  });
  if (result?.error) {
    logger.warn(`Part Stock not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived part stock with ID: ${id}`);
  res.send(result);
};

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

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

  const updateData = {};
  // Create audit log before updating
  const result = await editObject({
    model: partStockModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newPartStockRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    startingQuantity: req.body.startingQuantity,
    currentQuantity: req.body.currentQuantity,
    part: req.body.part,
    state: req.body.state,
  };
  const result = await newObject({
    model: partStockModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No part stock created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

export const getPartStockStatsRouteHandler = async (req, res) => {
  const result = await getModelStats({ model: partStockModel });
  if (result?.error) {
    logger.error('Error fetching part stock stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Part stock stats:', result);
  res.send(result);
};

export const getPartStockHistoryRouteHandler = async (req, res) => {
  const from = req.query.from;
  const to = req.query.to;
  const result = await getModelHistory({ model: partStockModel, from, to });
  if (result?.error) {
    logger.error('Error fetching part stock history:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Part stock history:', result);
  res.send(result);
};
