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

const shipmentItemSchema = new Schema({
  itemType: { type: String, required: true },
  item: { type: Schema.Types.ObjectId, refPath: 'itemType', required: true },
  quantity: { type: Number, required: true },
  itemCost: { type: Number, required: true },
  totalCost: { type: Number, required: true },
  totalCostWithTax: { type: Number, required: true },
  taxRate: { type: Schema.Types.ObjectId, ref: 'taxRate', required: false },
});

const shipmentSchema = new Schema(
  {
    _reference: { type: String, default: () => generateId()() },
    purchaseOrder: { type: Schema.Types.ObjectId, ref: 'purchaseOrder', required: true },
    vendor: { type: Schema.Types.ObjectId, ref: 'vendor', required: true },
    courierService: { type: Schema.Types.ObjectId, ref: 'courierService', required: false },
    trackingNumber: { type: String, required: false },
    items: [shipmentItemSchema],
    cost: { net: { type: Number, required: true }, gross: { type: Number, required: true } },
    shippedDate: { type: Date, required: false },
    expectedDeliveryDate: { type: Date, required: false },
    actualDeliveryDate: { type: Date, required: false },
    state: {
      type: {
        type: String,
        required: true,
        default: 'pending',
        enum: ['pending', 'shipped', 'in_transit', 'delivered', 'cancelled'],
      },
    },
    notes: { type: String },
    timestamp: { type: Date, default: Date.now },
  },
  { timestamps: true }
);

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

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

// Create and export the model
export const shipmentModel = mongoose.model('shipment', shipmentSchema);
