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

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

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

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

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

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

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

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

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

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

  const updateData = {
    updatedAt: new Date(),
    taxRate: req.body.taxRate,
    transactionType: req.body.transactionType,
    transaction: req.body.transaction,
    amount: req.body.amount,
    taxAmount: req.body.taxAmount,
    transactionDate: req.body.transactionDate,
  };
  // Create audit log before updating
  const result = await editObject({
    model: taxRecordModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const newTaxRecordRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    taxRate: req.body.taxRate,
    transactionType: req.body.transactionType,
    transaction: req.body.transaction,
    amount: req.body.amount,
    taxAmount: req.body.taxAmount,
    transactionDate: req.body.transactionDate,
  };
  const result = await newObject({
    model: taxRecordModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No tax record created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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