import dotenv from 'dotenv';
import { documentTemplateModel } from '../../database/schemas/management/documenttemplate.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 listDocumentTemplatesRouteHandler = async (
  req,
  res,
  page = 1,
  limit = 25,
  property = '',
  filter = {},
  search = '',
  sort = '',
  order = 'ascend'
) => {
  const result = await listObjects({
    model: documentTemplateModel,
    page,
    limit,
    property,
    filter,
    search,
    sort,
    order,
    populate: [
      { path: 'documentSize' },
      { path: 'parent' },
      { path: 'documentPrinters', strictPopulate: false },
    ],
  });

  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 listDocumentTemplatesByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {},
  masterFilter = {}
) => {
  const result = await listObjectsByProperties({
    model: documentTemplateModel,
    properties,
    filter,
    populate: ['documentSize'],
    masterFilter,
  });

  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 getDocumentTemplateRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: documentTemplateModel,
    id,
    populate: [
      { path: 'documentSize' },
      { path: 'parent', strictPopulate: false },
      { path: 'documentPrinters', strictPopulate: false },
    ],
  });
  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 editDocumentTemplateRouteHandler = 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,
    global: req.body.global,
    parent: req.body.parent,
    objectType: req.body.objectType,
    documentSize: req.body.documentSize,
    documentPrinters: req.body.documentPrinters,
    content: req.body.content,
    testObject: req.body.testObject,
  };
  // Create audit log before updating
  const result = await editObject({
    model: documentTemplateModel,
    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 newDocumentTemplateRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    name: req.body.name,
    tags: req.body.tags,
    active: req.body.active,
    global: req.body.global,
    parent: req.body.parent,
    objectType: req.body.objectType,
    documentSize: req.body.documentSize,
    documentPrinters: req.body.documentPrinters,
    content: req.body.content,
  };
  const result = await newObject({
    model: documentTemplateModel,
    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 deleteDocumentTemplateRouteHandler = 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: documentTemplateModel,
    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 getDocumentTemplateStatsRouteHandler = async (req, res) => {
  const result = await getModelStats({ model: documentTemplateModel });
  if (result?.error) {
    logger.error('Error fetching document template stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Document template stats:', result);
  res.send(result);
};

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