import config from '../../config.js';
import { invoiceModel } from '../../database/schemas/finance/invoice.schema.js';
import log4js from 'log4js';
import mongoose from 'mongoose';
import {
  deleteObject,
  listObjects,
  getObject,
  editObject,
  editObjects,
  newObject,
  listObjectsByProperties,
  getModelStats,
  getModelHistory,
  checkStates,
} from '../../database/database.js';

const logger = log4js.getLogger('Invoices');
logger.level = config.server.logLevel;

export const listInvoicesRouteHandler = async (
  req,
  res,
  page = 1,
  limit = 25,
  property = '',
  filter = {},
  search = '',
  sort = '',
  order = 'ascend'
) => {
  const populateFields = ['vendor', 'customer', 'relatedOrder'];
  const result = await listObjects({
    model: invoiceModel,
    page,
    limit,
    property,
    filter,
    search,
    sort,
    order,
    populate: populateFields,
  });

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

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

export const listInvoicesByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {},
  masterFilter = {}
) => {
  const populateFields = ['vendor', 'customer', 'relatedOrder'];
  const result = await listObjectsByProperties({
    model: invoiceModel,
    properties,
    filter,
    populate: populateFields,
    masterFilter,
  });

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

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

export const getInvoiceRouteHandler = async (req, res) => {
  const id = req.params.id;
  const populateFields = ['vendor', 'customer', 'relatedOrder'];
  const result = await getObject({
    model: invoiceModel,
    id,
    populate: populateFields,
  });
  if (result?.error) {
    logger.warn(`Invoice not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retrieved invoice with ID: ${id}`);
  res.send(result);
};

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

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

  const checkStatesResult = await checkStates({ model: invoiceModel, id, states: ['draft'] });

  if (checkStatesResult.error) {
    logger.error('Error checking invoice states:', checkStatesResult.error);
    res.status(checkStatesResult.code).send(checkStatesResult);
    return;
  }

  if (checkStatesResult === false) {
    logger.error('Invoice is not in draft state.');
    res.status(400).send({ error: 'Invoice is not in draft state.', code: 400 });
    return;
  }

  const updateData = {
    updatedAt: new Date(),
    vendor: req.body.vendor,
    customer: req.body.customer,
    invoiceType: req.body.invoiceType,
    invoiceDate: req.body.invoiceDate,
    dueDate: req.body.dueDate,
    relatedOrderType: req.body.relatedOrderType,
    relatedOrder: req.body.relatedOrder,
  };
  // Create audit log before updating
  const result = await editObject({
    model: invoiceModel,
    id,
    updateData,
    user: req.user,
  });

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

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

  res.send(result);
};

export const editMultipleInvoicesRouteHandler = async (req, res) => {
  const updates = req.body.map((update) => ({
    _id: update._id,
    vendor: update.vendor,
    customer: update.customer,
    invoiceType: update.invoiceType,
  }));

  if (!Array.isArray(updates)) {
    return res.status(400).send({ error: 'Body must be an array of updates.', code: 400 });
  }

  const result = await editObjects({
    model: invoiceModel,
    updates,
    user: req.user,
  });

  if (result.error) {
    logger.error('Error editing invoices:', result.error);
    res.status(result.code || 500).send(result);
    return;
  }

  logger.debug(`Edited ${updates.length} invoices`);

  res.send(result);
};

export const newInvoiceRouteHandler = async (req, res) => {
  const newData = {
    updatedAt: new Date(),
    vendor: req.body.vendor,
    customer: req.body.customer,
    invoiceType: req.body.invoiceType || 'sales',
    invoiceDate: req.body.invoiceDate || new Date(),
    dueDate: req.body.dueDate,
    relatedOrderType: req.body.relatedOrderType,
    relatedOrder: req.body.relatedOrder,
    totalAmount: 0,
    totalAmountWithTax: 0,
    totalTaxAmount: 0,
    grandTotalAmount: 0,
    shippingAmount: 0,
    shippingAmountWithTax: 0,
  };
  const result = await newObject({
    model: invoiceModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No invoice created:', result.error);
    return res.status(result.code).send(result);
  }

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

  res.send(result);
};

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

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

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

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

  res.send(result);
};

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

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

export const sendInvoiceRouteHandler = async (req, res) => {
  const id = new mongoose.Types.ObjectId(req.params.id);

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

  const checkStatesResult = await checkStates({ model: invoiceModel, id, states: ['draft'] });

  if (checkStatesResult.error) {
    logger.error('Error checking invoice states:', checkStatesResult.error);
    res.status(checkStatesResult.code).send(checkStatesResult);
    return;
  }

  if (checkStatesResult === false) {
    logger.error('Invoice is not in draft state.');
    res.status(400).send({ error: 'Invoice is not in draft state.', code: 400 });
    return;
  }

  const updateData = {
    updatedAt: new Date(),
    state: { type: 'sent' },
    sentAt: new Date(),
  };
  const result = await editObject({
    model: invoiceModel,
    id,
    updateData,
    user: req.user,
  });

  if (result.error) {
    logger.error('Error sending invoice:', result.error);
    res.status(result.code).send(result);
    return;
  }

  logger.debug(`Sent invoice with ID: ${id}`);
  res.send(result);
};

export const markInvoicePaidRouteHandler = async (req, res) => {
  const id = new mongoose.Types.ObjectId(req.params.id);

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

  const checkStatesResult = await checkStates({
    model: invoiceModel,
    id,
    states: ['sent', 'partiallyPaid'],
  });

  if (checkStatesResult.error) {
    logger.error('Error checking invoice states:', checkStatesResult.error);
    res.status(checkStatesResult.code).send(checkStatesResult);
    return;
  }

  if (checkStatesResult === false) {
    logger.error('Invoice is not in sent or partially paid state.');
    res.status(400).send({ error: 'Invoice is not in sent or partially paid state.', code: 400 });
    return;
  }

  const updateData = {
    updatedAt: new Date(),
    state: { type: 'paid' },
    paidAt: new Date(),
  };
  const result = await editObject({
    model: invoiceModel,
    id,
    updateData,
    user: req.user,
  });

  if (result.error) {
    logger.error('Error marking invoice as paid:', result.error);
    res.status(result.code).send(result);
    return;
  }

  logger.debug(`Marked invoice as paid with ID: ${id}`);
  res.send(result);
};

export const cancelInvoiceRouteHandler = async (req, res) => {
  const id = new mongoose.Types.ObjectId(req.params.id);

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

  const checkStatesResult = await checkStates({
    model: invoiceModel,
    id,
    states: ['draft', 'sent'],
  });

  if (checkStatesResult.error) {
    logger.error('Error checking invoice states:', checkStatesResult.error);
    res.status(checkStatesResult.code).send(checkStatesResult);
    return;
  }

  if (checkStatesResult === false) {
    logger.error('Invoice is not in a cancellable state.');
    res.status(400).send({
      error: 'Invoice is not in a cancellable state (must be draft or sent).',
      code: 400,
    });
    return;
  }

  const updateData = {
    updatedAt: new Date(),
    state: { type: 'cancelled' },
    cancelledAt: new Date(),
  };
  const result = await editObject({
    model: invoiceModel,
    id,
    updateData,
    user: req.user,
  });

  if (result.error) {
    logger.error('Error cancelling invoice:', result.error);
    res.status(result.code).send(result);
    return;
  }

  logger.debug(`Cancelled invoice with ID: ${id}`);
  res.send(result);
};
