import dotenv from 'dotenv';
import { userModel } from '../../database/schemas/management/user.schema.js';
import log4js from 'log4js';
import mongoose from 'mongoose';
import {
  listObjects,
  listObjectsByProperties,
  getObject,
  editObject,
  getModelStats,
  getModelHistory,
} from '../../database/database.js';

dotenv.config();

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

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

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

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

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

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

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

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

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

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

  const updateData = {
    updatedAt: new Date(),
    name: req.body.name,
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    email: req.body.email,
    profileImage: req.body.profileImage,
  };
  // Create audit log before updating
  const result = await editObject({
    model: userModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

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

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