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

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

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

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

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

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

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

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

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

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

  const updateData = {
    updatedAt: new Date(),
    name: req.body?.name,
    tags: req.body?.tags,
    version: req.body?.version,
    margin: req.body.margin,
    amount: req.body.amount,
    priceMode: req.body.priceMode,
    vendor: req.body.vendor,
    parts: req.body.parts,
  };
  // Create audit log before updating
  const result = await editObject({
    model: productModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newProductRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    name: req.body?.name,
    tags: req.body?.tags,
    version: req.body?.version,
    margin: req.body.margin,
    amount: req.body.amount,
    priceMode: req.body.priceMode,
    vendor: req.body.vendor,
    parts: req.body.parts,
  };

  const result = await newObject({
    model: productModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No product created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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