import mongoose, { Schema } from "mongoose";
import { nanoid } from "nanoid"; // To generate unique 6-char IDs

const orderItemSchema = new Schema({
  productId: {
    type: Schema.Types.ObjectId,
    ref: "Product",
    required: true,
  },
  SKU: {
    type: String,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  categoryName: {
    type: String, // Directly store category name
    required: true,
  },
  brandName: {
    type: String, // Directly store brand name
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  GST: {
    type: Number,
    required: true,
  },
  HSN_Code: {
    type: Number,
    required: true,
  },
  description: {
    type: String,
  },
  image: [
    {
      public_id: String,
      url: String,
    },
  ],
  quantity: {
    type: Number,
    required: true,
    default: 1,
  },
  remainingQuantity: {
    type: Number,
    required: true,
  },
});


const pdOrderSchema = new Schema(
  {
    paymentMode: {
      type: String,
      enum: ["cheque", "online-transfer", "credit"],
      required: true,
    },
    shipTo: {
      type: String,
      required: true,
    },
    billTo: {
      type: String,
      required: true,
    },
    orderItem: [orderItemSchema],
    subtotal: {
      type: Number,
      required: true,
    },
    gstTotal: {
      type: Number,
      required: true,
    },
    grandTotal: {
      type: Number,
      required: true,
    },
    status: { 
      type: String, 
      enum: ['new','pending','processing','dispatched', 'cancelled', 'delivered'], 
      default: 'new'
    },
    invoices: [
      { type: mongoose.Schema.Types.ObjectId, ref: 'Invoice' } 
    ],
    uniqueId: {
      type: String,
      unique: true,
      default: () => nanoid(6), // Generates a 6-character unique ID
    },
    addedBy: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    iscancelled: {
      type: Boolean,
      default: false,
    },
    order_Cancelled_Reason: {
      type: String,
    },
    isDelivered: { type: Boolean, required: true, default: false },
    DeliveredDate: { type: String, default: "" },
  },
  { timestamps: true }
);

// Middleware to generate uniqueId before saving the document
pdOrderSchema.pre('save', async function(next) {
  if (this.isNew) {
    const year = new Date().getFullYear().toString().slice(-2); // Get the last 2 digits of the year
    const orderItemCount = this.orderItem.length; // Count the number of order items
    const unique6CharId = nanoid(6); // Generate a 6-character unique ID

    this.uniqueId = `${year}-${orderItemCount}-${unique6CharId}`;
  }
  next();
});

export const PdOrder = mongoose.model("PdOrder", pdOrderSchema);

