import mongoose from 'mongoose';
import { purchaseOrderModel } from './purchaseorder.schema.js';
import { aggregateRollups, editObject } from '../../database.js';
import { generateId } from '../../utils.js';
const { Schema } = mongoose;

const orderItemSchema = new Schema(
  {
    _reference: { type: String, default: () => generateId()() },
    orderType: { type: String, required: true },
    order: { type: Schema.Types.ObjectId, refPath: 'orderType', required: true },
    itemType: { type: String, required: true },
    item: { type: Schema.Types.ObjectId, refPath: 'itemType', required: true },
    syncAmount: { type: String, required: true, default: null },
    itemAmount: { type: Number, required: true },
    quantity: { type: Number, required: true },
    totalAmount: { type: Number, required: true },
    taxRate: { type: Schema.Types.ObjectId, ref: 'taxRate', required: false },
    totalAmountWithTax: { type: Number, required: true },
    timestamp: { type: Date, default: Date.now },
  },
  { timestamps: true }
);

orderItemSchema.statics.recalculate = async function (orderItem, user) {
  // Only purchase orders are supported for now
  if (orderItem.orderType !== 'purchaseOrder') {
    return;
  }

  const orderId = orderItem.order?._id || orderItem.order;
  if (!orderId) {
    return;
  }

  const rollupResults = await aggregateRollups({
    model: this,
    baseFilter: {
      order: new mongoose.Types.ObjectId(orderId),
      orderType: orderItem.orderType,
    },
    rollupConfigs: [
      {
        name: 'orderTotals',
        rollups: [
          { name: 'totalAmount', property: 'totalAmount', operation: 'sum' },
          {
            name: 'totalAmountWithTax',
            property: 'totalAmountWithTax',
            operation: 'sum',
          },
        ],
      },
    ],
  });

  const totals = rollupResults.orderTotals || {};
  const totalAmount = totals.totalAmount.sum?.toFixed(2) || 0;
  const totalAmountWithTax = totals.totalAmountWithTax.sum?.toFixed(2) || 0;

  await editObject({
    model: purchaseOrderModel,
    id: orderId,
    updateData: {
      totalAmount: parseFloat(totalAmount),
      totalAmountWithTax: parseFloat(totalAmountWithTax),
      totalTaxAmount: parseFloat(totalAmountWithTax - totalAmount),
    },
    user,
  });
};

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

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

// Create and export the model
export const orderItemModel = mongoose.model('orderItem', orderItemSchema);
