import dotenv from 'dotenv';
import { gcodeFileModel } from '../../database/schemas/production/gcodefile.schema.js';
import log4js from 'log4js';
import {
  deleteObject,
  editObject,
  getObject,
  listObjects,
  listObjectsByProperties,
  newObject,
} from '../../database/database.js';
import { getFileContentRouteHandler } from '../management/files.js';
import mongoose from 'mongoose';

dotenv.config();

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

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

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

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

export const listGCodeFilesByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {}
) => {
  const result = await listObjectsByProperties({
    model: gcodeFileModel,
    properties,
    filter,
    populate: 'filament',
  });

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

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

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

export const getGCodeFileContentRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: gcodeFileModel,
    id,
  });

  if (result?.error) {
    logger.error('Error getting gcodeFile content.');
    res.status(result.code).send(result);
    return;
  }

  logger.debug(`Retreived gcodeFile content with ID: ${id}`);
  return getFileContentRouteHandler({ ...req, params: { id: result.file._id } }, res);
};

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

  logger.trace(`GCodeFile with ID: ${id}`);
  console.log('REQ.BODY', req.body);

  const updateData = {
    updatedAt: new Date(),
    name: req.body.name,
    file: req.body.file,
    filament: req.body.filament,
    parts: req.body.parts,
  };
  // Create audit log before updating
  const result = await editObject({
    model: gcodeFileModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newGCodeFileRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    name: req.body.name,
    file: req.body.file,
    filament: req.body.filament,
    parts: req.body.parts,
  };
  const result = await newObject({
    model: gcodeFileModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No gcodeFile created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

export const getGCodeFileStatsRouteHandler = async (req, res) => {
  try {
    const stats = await gcodeFileModel.aggregate([
      {
        $group: {
          _id: '$state.type',
          count: { $sum: 1 },
        },
      },
    ]);

    // Transform the results into a more readable format
    const formattedStats = stats.reduce((acc, curr) => {
      acc[curr._id] = curr.count;
      return acc;
    }, {});

    logger.trace('GCodeFile stats by state:', formattedStats);
    res.send(formattedStats);
  } catch (error) {
    logger.error('Error fetching gcodeFile stats:', error);
    res.status(500).send({ error: error.message });
  }
};
