import mongoose from 'mongoose';
import { generateId } from '../../utils.js';
const { Schema } = mongoose;
import { aggregateRollups, aggregateRollupsHistory } from '../../database.js';

const invoiceSchema = new Schema(
  {
    _reference: { type: String, default: () => generateId()() },
    totalAmount: { type: Number, required: true, default: 0 },
    totalAmountWithTax: { type: Number, required: true, default: 0 },
    shippingAmount: { type: Number, required: true, default: 0 },
    shippingAmountWithTax: { type: Number, required: true, default: 0 },
    grandTotalAmount: { type: Number, required: true, default: 0 },
    totalTaxAmount: { type: Number, required: true, default: 0 },
    timestamp: { type: Date, default: Date.now },
    invoiceDate: { type: Date, required: false },
    dueDate: { type: Date, required: false },
    vendor: { type: Schema.Types.ObjectId, ref: 'vendor', required: false },
    customer: { type: Schema.Types.ObjectId, ref: 'customer', required: false },
    invoiceType: { type: String, required: true, default: 'sales', enum: ['sales', 'purchase'] },
    relatedOrderType: { type: String, required: false },
    relatedOrder: { type: Schema.Types.ObjectId, refPath: 'relatedOrderType', required: false },
    state: {
      type: { type: String, required: true, default: 'draft' },
    },
    sentAt: { type: Date, required: false },
    paidAt: { type: Date, required: false },
    cancelledAt: { type: Date, required: false },
    overdueAt: { type: Date, required: false },
  },
  { timestamps: true }
);

const rollupConfigs = [
  {
    name: 'draft',
    filter: { 'state.type': 'draft' },
    rollups: [{ name: 'draft', property: 'state.type', operation: 'count' }],
  },
  {
    name: 'sent',
    filter: { 'state.type': 'sent' },
    rollups: [{ name: 'sent', property: 'state.type', operation: 'count' }],
  },
  {
    name: 'partiallyPaid',
    filter: { 'state.type': 'partiallyPaid' },
    rollups: [{ name: 'partiallyPaid', property: 'state.type', operation: 'count' }],
  },
  {
    name: 'paid',
    filter: { 'state.type': 'paid' },
    rollups: [{ name: 'paid', property: 'state.type', operation: 'count' }],
  },
  {
    name: 'overdue',
    filter: { 'state.type': 'overdue' },
    rollups: [{ name: 'overdue', property: 'state.type', operation: 'count' }],
  },
  {
    name: 'cancelled',
    filter: { 'state.type': 'cancelled' },
    rollups: [{ name: 'cancelled', property: 'state.type', operation: 'count' }],
  },
];

invoiceSchema.statics.stats = async function () {
  const results = await aggregateRollups({
    model: this,
    rollupConfigs: rollupConfigs,
  });

  // Transform the results to match the expected format
  return results;
};

invoiceSchema.statics.history = async function (from, to) {
  const results = await aggregateRollupsHistory({
    model: this,
    startDate: from,
    endDate: to,
    rollupConfigs: rollupConfigs,
  });

  // Return time-series data array
  return results;
};

// Add virtual id getter
invoiceSchema.virtual('id').get(function () {
  return this._id;
});

// Configure JSON serialization to include virtuals
invoiceSchema.set('toJSON', { virtuals: true });

// Create and export the model
export const invoiceModel = mongoose.model('invoice', invoiceSchema);
