import dotenv from 'dotenv';
import { documentSizeModel } from '../../database/schemas/management/documentsize.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('Document Sizes');
logger.level = process.env.LOG_LEVEL;

export const listDocumentSizesRouteHandler = async (
  req,
  res,
  page = 1,
  limit = 25,
  property = '',
  filter = {},
  search = '',
  sort = '',
  order = 'ascend'
) => {
  const result = await listObjects({
    model: documentSizeModel,
    page,
    limit,
    property,
    filter,
    search,
    sort,
    order,
  });

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

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

export const listDocumentSizesByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {}
) => {
  const result = await listObjectsByProperties({
    model: documentSizeModel,
    properties,
    filter,
  });

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

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

export const getDocumentSizeRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: documentSizeModel,
    id,
  });
  if (result?.error) {
    logger.warn(`Document size not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived document size with ID: ${id}`);
  res.send(result);
};

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

  logger.trace(`Document size with ID: ${id}`);

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

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

  logger.debug(`Edited document size with ID: ${id}`);

  res.send(result);
};

export const newDocumentSizeRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    name: req.body.name,
    width: req.body.width,
    height: req.body.height,
    infiniteHeight: req.body.infiniteHeight,
  };
  const result = await newObject({
    model: documentSizeModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No document size created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

  logger.trace(`Document size with ID: ${id}`);

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

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

  res.send(result);
};

export const getDocumentSizeStatsRouteHandler = async (req, res) => {
  const result = await getModelStats({ model: documentSizeModel });
  if (result?.error) {
    logger.error('Error fetching document size stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Document size stats:', result);
  res.send(result);
};

export const getDocumentSizeHistoryRouteHandler = async (req, res) => {
  const from = req.query.from;
  const to = req.query.to;
  const result = await getModelHistory({ model: documentSizeModel, from, to });
  if (result?.error) {
    logger.error('Error fetching document size history:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Document size history:', result);
  res.send(result);
};
