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

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

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

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

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

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

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

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

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

  logger.trace(`Vendor 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,
    address: req.body.address,
    active: req.body.active,
  };
  // Create audit log before updating
  const result = await editObject({
    model: vendorModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newVendorRouteHandler = 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,
    address: req.body.address,
    active: req.body.active,
  };
  const result = await newObject({
    model: vendorModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No vendor created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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