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

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

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

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

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

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

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

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

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

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

  const updateData = {
    updatedAt: new Date(),
    courier: req.body?.courier,
    website: req.body?.website,
    deliveryTime: req.body?.deliveryTime,
    active: req.body?.active,
    tracked: req.body?.tracked,
    name: req.body?.name,
  };
  // Create audit log before updating
  const result = await editObject({
    model: courierServiceModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newCourierServiceRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    courier: req.body?.courier,
    website: req.body?.website,
    deliveryTime: req.body?.deliveryTime,
    active: req.body?.active,
    tracked: req.body?.tracked,
    name: req.body?.name,
  };
  const result = await newObject({
    model: courierServiceModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No courier service created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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