import dotenv from 'dotenv';
import { noteModel } from '../../database/schemas/misc/note.schema.js';
import log4js from 'log4js';
import {
  deleteObject,
  editObject,
  getObject,
  listObjects,
  listObjectsByProperties,
  newObject,
  recursivelyDeleteChildObjects,
  getModelStats,
  getModelHistory,
} from '../../database/database.js';
import mongoose from 'mongoose';

dotenv.config();

const logger = log4js.getLogger('Notes');
logger.level = process.env.LOG_LEVEL;

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

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

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

export const listNotesByPropertiesRouteHandler = async (req, res, properties = '', filter = {}) => {
  const result = await listObjectsByProperties({
    model: noteModel,
    properties,
    filter,
    populate: ['noteType', 'user'],
  });

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

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

export const getNoteRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: noteModel,
    id,
    populate: ['noteType', 'user', 'parent'],
  });
  if (result?.error) {
    logger.warn(`Note not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived note with ID: ${id}`);
  res.send(result);
};

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

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

  const updateData = {
    updatedAt: new Date(),
    content: req.body.content,
    noteType: req.body.noteType,
  };
  // Create audit log before updating
  const result = await editObject({
    model: noteModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newNoteRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    content: req.body.content,
    noteType: req.body.noteType,
    parent: req.body.parent,
    parentType: req.body.parentType,
    user: req.user,
  };
  const result = await newObject({
    model: noteModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No note created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

export const deleteNoteRouteHandler = async (req, res) => {
  // Get ID from params
  const id = req.params.id;

  logger.trace(`Delete note with ID: ${id}`);

  // Recursively find and delete all child notes
  const result = await recursivelyDeleteChildObjects({ model: noteModel, id, user: req.user });

  if (result?.length <= 0) {
    logger.error('No notes deleted');
    return res.status(404).send(result);
  }

  if (result?.error) {
    logger.error('No note deleted:', result.error);
    return res.status(result.code).send(result);
  }

  logger.info(`Successfully deleted note ${id} and ${result.length - 1} child notes`);
  res.send({
    status: 'ok',
  });
};

export const getNoteStatsRouteHandler = async (req, res) => {
  const result = await getModelStats({ model: noteModel });
  if (result?.error) {
    logger.error('Error fetching note stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Note stats:', result);
  res.send(result);
};

export const getNoteHistoryRouteHandler = async (req, res) => {
  const from = req.query.from;
  const to = req.query.to;
  const result = await getModelHistory({ model: noteModel, from, to });
  if (result?.error) {
    logger.error('Error fetching note history:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Note history:', result);
  res.send(result);
};
