import dotenv, { populate } from 'dotenv';
import { filamentModel } from '../../database/schemas/management/filament.schema.js';
import log4js from 'log4js';
import mongoose from 'mongoose';
import {
  getObject,
  listObjects,
  listObjectsByProperties,
  editObject,
  newObject,
  getModelStats,
  getModelHistory,
} from '../../database/database.js';

dotenv.config();
const logger = log4js.getLogger('Filaments');
logger.level = process.env.LOG_LEVEL;

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

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

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

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

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

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

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

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

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

  const updateData = {
    updatedAt: new Date(),
    name: req.body.name,
    barcode: req.body.barcode,
    url: req.body.url,
    image: req.body.image,
    color: req.body.color,
    vendor: req.body.vendor,
    type: req.body.type,
    cost: req.body.cost,
    costTaxRate: req.body.costTaxRate,
    costWithTax: req.body.costWithTax,
    diameter: req.body.diameter,
    density: req.body.density,
    emptySpoolWeight: req.body.emptySpoolWeight,
  };
  const result = await editObject({
    model: filamentModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newFilamentRouteHandler = async (req, res) => {
  const newData = {
    createdAt: new Date(),
    updatedAt: new Date(),
    name: req.body.name,
    barcode: req.body.barcode,
    url: req.body.url,
    image: req.body.image,
    color: req.body.color,
    vendor: req.body.vendor,
    type: req.body.type,
    cost: req.body.cost,
    costTaxRate: req.body.costTaxRate,
    costWithTax: req.body.costWithTax,
    diameter: req.body.diameter,
    density: req.body.density,
    emptySpoolWeight: req.body.emptySpoolWeight,
  };

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

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

  res.send(result);
};

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

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