import dotenv from 'dotenv';
import { printerModel } from '../../database/schemas/production/printer.schema.js';
import log4js from 'log4js';
import {
  deleteObject,
  editObject,
  getObject,
  listObjects,
  listObjectsByProperties,
  newObject,
  getModelStats,
  getModelHistory,
} from '../../database/database.js';
import mongoose from 'mongoose';

dotenv.config();

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

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

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

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

export const listPrintersByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {}
) => {
  const result = await listObjectsByProperties({
    model: printerModel,
    properties,
    filter,
    populate: ['vendor', 'host'],
  });

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

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

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

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

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

  const updateData = {
    updatedAt: new Date(),
    name: req.body.name,
    moonraker: req.body.moonraker,
    tags: req.body.tags,
    vendor: req.body.vendor,
    host: req.body.host,
    active: req.body.active,
  };
  // Create audit log before updating
  const result = await editObject({
    model: printerModel,
    id,
    updateData,
    user: req.user,
    populate: 'vendor',
  });

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

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

  res.send(result);
};

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

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

export const getPrinterStatsRouteHandler = async (req, res) => {
  const result = await getModelStats({ model: printerModel });
  console.log(result);
  if (!result) {
    logger.error('Error fetching printer stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Printer stats:', result);
  res.send(result);
};

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