import mongoose from "mongoose";

const orderItemSchema = new mongoose.Schema({
  product: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
  vendor: { type: mongoose.Schema.Types.ObjectId, ref: "Vendor" },
  name: String,
  quantity: Number,
  price: Number,
  printConfig: {
    service: String,
    size: String,
    material: String,
    artworkUrl: String,
    approvalStatus: { type: String, enum: ["pending", "approved", "revision_requested"], default: "pending" },
    notes: String
  }
});

const orderSchema = new mongoose.Schema(
  {
    customer: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
    items: [orderItemSchema],
    status: {
      type: String,
      enum: ["Pending", "Processing", "Packed", "Shipped", "Out for delivery", "Delivered", "Cancelled"],
      default: "Pending",
      index: true
    },
    subtotal: Number,
    deliveryFee: Number,
    discount: Number,
    total: Number,
    paymentMethod: { type: String, enum: ["paystack", "flutterwave", "stripe", "bank_transfer", "wallet", "cod"] },
    paymentStatus: { type: String, enum: ["pending", "verified", "failed", "refunded"], default: "pending" },
    deliveryAddress: Object,
    tracking: {
      rider: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
      trackingCode: String,
      events: [{ status: String, note: String, location: String, createdAt: { type: Date, default: Date.now } }]
    }
  },
  { timestamps: true }
);

export const Order = mongoose.model("Order", orderSchema);
