import dotenv from 'dotenv';
import { subJobModel } from '../../database/schemas/production/subjob.schema.js';
import log4js from 'log4js';
import {
  getObject,
  listObjects,
  listObjectsByProperties,
  getModelStats,
  getModelHistory,
} from '../../database/database.js';
dotenv.config();

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

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

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

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

export const listSubJobsByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {},
  masterFilter = {}
) => {
  const result = await listObjectsByProperties({
    model: subJobModel,
    properties,
    filter,
    masterFilter,
  });

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

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

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

export const getSubJobStatsRouteHandler = async (req, res) => {
  const result = await getModelStats({ model: subJobModel });
  if (result?.error) {
    logger.error('Error fetching sub job stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Sub job stats:', result);
  res.send(result);
};

export const getSubJobHistoryRouteHandler = async (req, res) => {
  const from = req.query.from;
  const to = req.query.to;
  const result = await getModelHistory({ model: subJobModel, from, to });
  if (result?.error) {
    logger.error('Error fetching sub job history:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Sub job history:', result);
  res.send(result);
};
