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

export interface IUserAddress extends Document {
  user: mongoose.Types.ObjectId;

  name: string;
  phone: string;

  addressLine1: string;
  addressLine2?: string;

  city: string;

  state: mongoose.Types.ObjectId;

  pincode: string;

  isDefault: boolean;

  createdAt: Date;
  updatedAt: Date;
}

const UserAddressSchema = new Schema<IUserAddress>(
  {
    user: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: [true, "User is required"],
      index: true,
    },

    name: {
      type: String,
      required: [true, "Name is required"],
      trim: true,
      maxlength: [200, "Name cannot exceed 200 characters"],
    },

    phone: {
      type: String,
      required: [true, "Phone number is required"],
      trim: true,
    },

    addressLine1: {
      type: String,
      required: [true, "Address is required"],
      trim: true,
      maxlength: [500, "Address cannot exceed 500 characters"],
    },

    addressLine2: {
      type: String,
      trim: true,
      default: "",
    },

    city: {
      type: String,
      required: [true, "City is required"],
      trim: true,
      maxlength: [100, "City cannot exceed 100 characters"],
    },

    state: {
      type: Schema.Types.ObjectId,
      ref: "State",
      required: [true, "State is required"],
    },

    pincode: {
      type: String,
      required: [true, "Pincode is required"],
      trim: true,
    },

    isDefault: {
      type: Boolean,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);

// Indexes
UserAddressSchema.index({ user: 1 });
UserAddressSchema.index({ user: 1, isDefault: 1 });

export default mongoose.models.UserAddress ||
  mongoose.model<IUserAddress>("UserAddress", UserAddressSchema);