import mongoose, { Document, Schema } from 'mongoose';

// Order item interface
export interface IOrderItem {
  product_id: string;
  product_sku: string;
  product_name: string;
  price: number;
  quantity: number;
  subtotal: number;
}

// Delivery address interface
export interface IDeliveryAddress {
  full_name: string;
  phone: string;
  address_line1: string;
  address_line2?: string;
  city: string;
  state: string;
  pincode: string;
  country: string;
}

export interface IOrder extends Document {
  order_id: string;

    // Customer IDs
  customer_id?: mongoose.Schema.Types.ObjectId;
  guest_id?: string;

  // Customer
  customer_name: string;
  customer_phone: string;
  customer_email: string;

  // Products ordered
  items: IOrderItem[];

  // Address
  delivery_address: IDeliveryAddress;

  // Payment
  payment_status: 'pending' | 'paid' | 'failed' | 'refunded';
  payment_method: 'cod' | 'online' | 'upi';
  payment_id?: string; // payment gateway ID

  // Amounts
  subtotal: number;
  shipping_charge: number;
  discount: number;
  total_amount: number;

  // Status
  order_status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled';

  // Shipment reference ← connects to Shipment model
  shipment_id?: mongoose.Schema.Types.ObjectId;

  device: 'website' | 'mobile' | 'admin';
  order_placed_at: Date;
  createdAt: Date;
  updatedAt: Date;
}

const OrderItemSchema = new Schema({
  product_id: { type: String, required: true },
  product_sku: { type: String, required: true },
  product_name: { type: String, required: true },

  price: { type: Number, required: true },
  quantity: { type: Number, required: true, min: 1 },
  subtotal: { type: Number, required: true },
});

const DeliveryAddressSchema = new Schema({
  full_name: { type: String, required: true },
  phone: { type: String, required: true },
  address_line1: { type: String, required: true },
  address_line2: { type: String },
  city: { type: String, required: true },
  state: { type: String, required: true },
  pincode: { type: String, required: true },
  country: { type: String, default: 'India' },
});

const OrderSchema: Schema = new Schema(
  {
    order_id: {
      type: String,
      required: true,
      unique: true,
      trim: true,
    },
    customer_id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      default: null,
    },

    guest_id: {
      type: String,
      default: null,
    },

    customer_name: { type: String, required: true, trim: true },
    customer_phone: { type: String, required: true, trim: true },
    customer_email: { type: String, required: true, trim: true, lowercase: true },

    // ✅ Products
    items: {
      type: [OrderItemSchema],
      required: true,
      validate: {
        validator: (v: IOrderItem[]) => v.length > 0,
        message: 'Order must have at least one item',
      },
    },

    // ✅ Address
    delivery_address: {
      type: DeliveryAddressSchema,
      required: true,
    },

    // ✅ Payment
    payment_status: {
      type: String,
      enum: ['pending', 'paid', 'failed', 'refunded'],
      default: 'pending',
    },
    payment_method: {
      type: String,
      enum: ['cod', 'online', 'upi'],
      default: 'cod',
    },
    payment_id: { type: String },

    // ✅ Amounts
    subtotal: { type: Number, required: true, min: 0 },
    shipping_charge: { type: Number, default: 0 },
    discount: { type: Number, default: 0 },
    total_amount: { type: Number, required: true, min: 0 },

    // ✅ Status
    order_status: {
      type: String,
      enum: ['pending', 'processing', 'shipped', 'delivered', 'cancelled'],
      default: 'pending',
    },

    // ✅ Shipment reference
    shipment_id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Shipment',
    },

    device: {
      type: String,
      enum: ['website', 'mobile', 'admin'],
      default: 'website',
    },

    order_placed_at: {
      type: Date,
      default: Date.now,
    },
  },
  { timestamps: true }
);

// Indexes
OrderSchema.index({ order_id: 1 });
OrderSchema.index({ customer_email: 1 });
OrderSchema.index({ order_status: 1 });
OrderSchema.index({ order_placed_at: -1 });

// Auto-generate Order ID
OrderSchema.pre('validate', function (this: IOrder) {
  if (!this.order_id) {
    const random = Math.random().toString(36).substring(2, 8).toUpperCase();
    this.order_id = `DS${Date.now()}${random}`;
  }
});

export default mongoose.models.Order || mongoose.model<IOrder>('Order', OrderSchema);