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

// Define the main partStock schema
const partStockSchema = new Schema(
  {
    _reference: { type: String, default: () => generateId()() },
    state: {
      type: { type: String, required: true },
      progress: { type: Number, required: false },
    },
    part: { type: mongoose.Schema.Types.ObjectId, ref: 'part', required: true },
    currentQuantity: { type: Number, required: true },
    sourceType: { type: String, required: true },
    source: { type: Schema.Types.ObjectId, refPath: 'sourceType', required: true },
  },
  { timestamps: true }
);

const rollupConfigs = [
  {
    name: 'totalCurrentQuantity',
    filter: {},
    rollups: [{ name: 'totalCurrentQuantity', property: 'currentQuantity', operation: 'sum' }],
  },
];

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

  return results;
};

partStockSchema.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
partStockSchema.virtual('id').get(function () {
  return this._id;
});

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

// Create and export the model
export const partStockModel = mongoose.model('partStock', partStockSchema);
