import dotenv from 'dotenv';
import { noteTypeModel } from '../../database/schemas/management/notetype.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('Note Types');
logger.level = process.env.LOG_LEVEL;

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

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

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

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

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

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

export const getNoteTypeRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: noteTypeModel,
    id,
  });
  if (result?.error) {
    logger.warn(`Note Type not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived note type with ID: ${id}`);
  res.send(result);
};

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

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

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

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

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

  res.send(result);
};

export const newNoteTypeRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    name: req.body.name,
    color: req.body.color,
    active: req.body.active,
  };
  const result = await newObject({
    model: noteTypeModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No note type created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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