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

const partSchema = new Schema({
  part: { type: Schema.Types.ObjectId, ref: 'part', required: true },
  quantity: { type: Number, required: true },
});

// Define the main product schema
const productSchema = new Schema(
  {
    _reference: { type: String, default: () => generateId()() },
    name: { type: String, required: true },
    tags: [{ type: String }],
    version: { type: String },
    priceMode: { type: String, default: 'margin' },
    margin: { type: Number, required: false },
    amount: { type: Number, required: false },
    vendor: { type: Schema.Types.ObjectId, ref: 'vendor', required: true },
    parts: [partSchema],
    priceTaxRate: { type: Schema.Types.ObjectId, ref: 'taxRate', required: false },
    costTaxRate: { type: Schema.Types.ObjectId, ref: 'taxRate', required: false },
  },
  { timestamps: true }
);
// Add virtual id getter
productSchema.virtual('id').get(function () {
  return this._id;
});

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

// Create and export the model
export const productModel = mongoose.model('product', productSchema);
