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

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

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

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

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

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

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

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

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

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

  const updateData = {
    updatedAt: new Date(),
    name: req.body.name,
    rate: req.body.rate,
    rateType: req.body.rateType,
    active: req.body.active,
    description: req.body.description,
    country: req.body.country,
    effectiveFrom: req.body.effectiveFrom,
    effectiveTo: req.body.effectiveTo,
  };
  // Create audit log before updating
  const result = await editObject({
    model: taxRateModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newTaxRateRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    name: req.body.name,
    rate: req.body.rate,
    rateType: req.body.rateType,
    active: req.body.active,
    description: req.body.description,
    country: req.body.country,
    effectiveFrom: req.body.effectiveFrom,
    effectiveTo: req.body.effectiveTo,
  };
  const result = await newObject({
    model: taxRateModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No tax rate created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

export const getTaxRateStatsRouteHandler = async (req, res) => {
  const result = await getModelStats({ model: taxRateModel });
  if (result?.error) {
    logger.error('Error fetching tax rate stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Tax rate stats:', result);
  res.send(result);
};

export const getTaxRateHistoryRouteHandler = async (req, res) => {
  const from = req.query.from;
  const to = req.query.to;
  const result = await getModelHistory({ model: taxRateModel, from, to });
  if (result?.error) {
    logger.error('Error fetching tax rate history:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Tax rate history:', result);
  res.send(result);
};
