import mongoose from 'mongoose';
import { generateId } from '../../utils.js';
const { Schema } = mongoose;

const stockAuditItemSchema = new Schema({
  type: { type: String, enum: ['filament', 'part'], required: true },
  stock: { type: Schema.Types.ObjectId, required: true },
  expectedQuantity: { type: Number, required: true },
  actualQuantity: { type: Number, required: true },
  notes: { type: String },
});

const stockAuditSchema = new Schema(
  {
    _reference: { type: String, default: () => generateId()() },
    type: { type: String, required: true },
    status: {
      type: String,
      enum: ['pending', 'in_progress', 'completed', 'cancelled'],
      default: 'pending',
      required: true,
    },
    notes: { type: String },
    items: [stockAuditItemSchema],
    createdBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
    completedAt: { type: Date },
  },
  { timestamps: true }
);

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

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

// Create and export the model
export const stockAuditModel = mongoose.model('stockAudit', stockAuditSchema);
