import dotenv from 'dotenv';
import { stockEventModel } from '../../database/schemas/inventory/stockevent.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('Stock Events');
logger.level = process.env.LOG_LEVEL;

export const listStockEventsRouteHandler = async (
  req,
  res,
  page = 1,
  limit = 25,
  filter = {},
  sort = '',
  order = 'ascend'
) => {
  const result = await listObjects({
    model: stockEventModel,
    page,
    limit,
    filter,
    sort,
    order,
    populate: [
      { path: 'owner', select: 'name _id' },
      { path: 'parent', select: 'name _id' },
    ],
  });

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

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

export const listStockEventsByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {},
  masterFilter = {}
) => {
  const result = await listObjectsByProperties({
    model: stockEventModel,
    properties,
    filter,
    populate: [
      { path: 'owner', select: 'name _id' },
      { path: 'parent', select: 'name _id' },
    ],
    masterFilter,
  });

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

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

export const getStockEventRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: stockEventModel,
    id,
    populate: [
      { path: 'owner', select: 'name _id' },
      { path: 'parent', select: 'name _id' },
    ],
  });
  if (result?.error) {
    logger.warn(`Stock event not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retrieved stock event with ID: ${id}`);
  res.send(result);
};

export const newStockEventRouteHandler = async (req, res) => {
  const newData = {
    value: req.body.value,
    current: req.body.current,
    unit: req.body.unit,
    parent: req.body.parent,
    parentType: req.body.parentType,
    owner: req.body.owner,
    ownerType: req.body.ownerType,
    timestamp: req.body.timestamp || new Date(),
  };
  const result = await newObject({
    model: stockEventModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No stock event created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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