import dotenv from 'dotenv';
import { documentPrinterModel } from '../../database/schemas/management/documentprinter.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 Templates');
logger.level = process.env.LOG_LEVEL;

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

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

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

export const listDocumentPrintersByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {}
) => {
  const result = await listObjectsByProperties({
    model: documentPrinterModel,
    properties,
    filter,
    populate: ['currentDocumentSize', 'host'],
  });

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

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

export const getDocumentPrinterRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: documentPrinterModel,
    id,
    populate: ['currentDocumentSize', 'host'],
  });
  if (result?.error) {
    logger.warn(`Document Template not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived document template with ID: ${id}`);
  res.send(result);
};

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

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

  const updateData = {
    updatedAt: new Date(),
    name: req.body.name,
    tags: req.body.tags,
    active: req.body.active,
    connection: req.body.connection,
    currentDocumentSize: req.body.currentDocumentSize,
    host: req.body.host,
  };
  // Create audit log before updating
  const result = await editObject({
    model: documentPrinterModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newDocumentPrinterRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    name: req.body.name,
    tags: req.body.tags,
    active: req.body.active,
    connection: req.body.connection,
    currentDocumentSize: req.body.currentDocumentSize,
    host: req.body.host,
  };
  const result = await newObject({
    model: documentPrinterModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No document template created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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