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 rdOrderSchema = 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: "InvoiceRd" }, // Similar to PdOrder invoices
    ],
    statusUpdatedAt: {
      type: Date,
      default: Date.now,
    },
    uniqueId: {
      type: String,
      unique: true,
      default: () => nanoid(6), // Generates a 6-character unique ID
    },
    addedBy: {
      type: Schema.Types.ObjectId,
      ref: "RetailDistributor", // Reference to the RD placing the order
      required: true,
    },
    pd: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User", // Reference to the PD associated with the RD
      required: true,
    },
    // status_timeline: {
    //   new: { type: Date },
    //   paid: { type: Date },
    //   processing: { type: Date },
    //   dispatched: { type: Date },
    //   delivered: { type: Date },
    //   cancelled: { type: Date },
    //   returned: { type: Date },
    // },

    iscancelled: {
      type: Boolean,
      default: false,
    },
    order_Cancelled_Reason: {
      type: String,
    },
    courier_name: { type: String },
    courier_tracking_id: { type: String },
    isDelivered: { type: Boolean, required: true, default: false },
    DeliveredDate: { type: String, default: "" },
    // To store the status history
  },
  { timestamps: true }
);

// Middleware to generate uniqueId and update statusHistory
rdOrderSchema.pre("save", 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 RdOrder = mongoose.model("RdOrder", rdOrderSchema);
