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

export const listCouriersRouteHandler = async (
  req,
  res,
  page = 1,
  limit = 25,
  property = '',
  filter = {},
  search = '',
  sort = '',
  order = 'ascend'
) => {
  const result = await listObjects({
    model: courierModel,
    page,
    limit,
    property,
    filter,
    search,
    sort,
    order,
  });

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

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

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

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

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

export const getCourierRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: courierModel,
    id,
  });
  if (result?.error) {
    logger.warn(`Courier not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived courier with ID: ${id}`);
  res.send(result);
};

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

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

  const updateData = {
    updatedAt: new Date(),
    contact: req.body?.contact,
    country: req.body?.country,
    name: req.body?.name,
    website: req.body?.website,
    phone: req.body?.phone,
    email: req.body?.email,
  };
  // Create audit log before updating
  const result = await editObject({
    model: courierModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newCourierRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    contact: req.body?.contact,
    country: req.body?.country,
    name: req.body?.name,
    website: req.body?.website,
    phone: req.body?.phone,
    email: req.body?.email,
  };
  const result = await newObject({
    model: courierModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No courier created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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