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

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

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

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

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

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

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

export const getDocumentJobRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: documentJobModel,
    id,
    populate: ['documentTemplate', 'documentPrinter', 'object'],
  });
  if (result?.error) {
    logger.warn(`Document Job not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived document job with ID: ${id}`);
  res.send(result);
};

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

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

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

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

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

  res.send(result);
};

export const newDocumentJobRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    name: req.body.name,
    documentPrinter: req.body.documentPrinter,
    documentTemplate: req.body.documentTemplate,
    objectType: req.body.objectType,
    object: req.body.object,
    content: req.body.content,
    state: { type: 'draft' },
    createdAt: new Date(),
    updatedAt: new Date(),
  };
  const result = await newObject({
    model: documentJobModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No document job created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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