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

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

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

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

export const listPartsByPropertiesRouteHandler = async (req, res, properties = '', filter = {}) => {
  const result = await listObjectsByProperties({
    model: partModel,
    properties,
    filter,
    populate: [
      {
        path: 'vendor',
        from: 'vendors',
      },
      {
        path: 'priceTaxRate',
        from: 'taxrates',
      },
      {
        path: 'costTaxRate',
        from: 'taxrates',
      },
    ],
  });

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

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

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

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

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

  const updateData = {
    updatedAt: new Date(),
    name: req.body?.name,
    file: req.body?.file,
    vendor: req.body?.vendor,
    margin: req.body?.margin,
    price: req.body?.price,
    cost: req.body?.cost,
    priceMode: req.body?.priceMode,
    priceTaxRate: req.body?.priceTaxRate,
    costTaxRate: req.body?.costTaxRate,
    priceWithTax: req.body?.priceWithTax,
    costWithTax: req.body?.costWithTax,
  };
  // Create audit log before updating
  const result = await editObject({
    model: partModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newPartRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    name: req.body?.name,
    file: req.body?.file,
    vendor: req.body?.vendor,
    margin: req.body?.margin,
    price: req.body?.price,
    cost: req.body?.cost,
    priceMode: req.body?.priceMode,
    priceTaxRate: req.body?.priceTaxRate,
    costTaxRate: req.body?.costTaxRate,
    priceWithTax: req.body?.priceWithTax,
    costWithTax: req.body?.costWithTax,
  };

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

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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