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

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

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

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

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

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

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

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

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

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

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

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

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

  res.send(result);
};

export const newFilamentStockRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    startingWeight: req.body.startingWeight,
    currentWeight: req.body.currentWeight,
    filament: req.body.filament,
    state: req.body.state,
  };
  const result = await newObject({
    model: filamentStockModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No filament stock created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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