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

// Define the main part schema
const partSchema = new Schema(
  {
    _reference: { type: String, default: () => generateId()() },
    name: { type: String, required: true },
    fileName: { type: String, required: false },
    priceMode: { type: String, default: 'margin' },
    price: { type: Number, required: true },
    cost: { type: Number, required: true },
    margin: { type: Number, required: false },
    vendor: { type: Schema.Types.ObjectId, ref: 'vendor', required: true },
    file: { type: mongoose.SchemaTypes.ObjectId, ref: 'file', required: false },
    priceTaxRate: { type: Schema.Types.ObjectId, ref: 'taxRate', required: false },
    costTaxRate: { type: Schema.Types.ObjectId, ref: 'taxRate', required: false },
    priceWithTax: { type: Number, required: false },
    costWithTax: { type: Number, required: false },
  },
  { timestamps: true }
);

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

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

// Create and export the model
export const partModel = mongoose.model('part', partSchema);
