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

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

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

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

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

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

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

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

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

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

  const updateData = {
    updatedAt: new Date(),
    name: req.body.name,
    active: req.body.active,
    tags: req.body.tags,
    files: req.body.files,
  };

  const result = await editObject({
    model: hostModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

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

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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