const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Account',
    required: true,
  },
  brand: {
    type: String,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  imageUrl: {
    type: String,
    required: true,
    default: 'https://example.com/default-product-image.jpg',
  },
  otherImages: {
    type: Array,
    required: true,
  },
  stock: {
    type: Number,
    required: true,
    default: 0,
  },
  isActive: {
    type: Boolean,
    required: true,
    default: true,
  },
  swappable: {
    type: Boolean,
    required: true,
    default: false,
  },
  installmentAvailable: {
    type: Boolean,
    required: true,
    default: false,
  },
  installmentTotalAmount: {
    type: Number,
    required: true,
    default: 0,
  },
  installmentPlans: {
    type: Array,
    required: true,
    default: [],
  },
  views: {
    type: Number,
    required: true,
    default: 0,
  },
  approved: {
    type: Boolean,
    required: true,
    default: false,
  },
  conditionTag: {
    type: String,
    required: true,
    enum: ['EXCELLENT', 'GOOD', 'FAIR'],
    default: null,
  },
  verificationStatus: {
    type: String,
    required: true,
    enum: ['VERIFY', 'WARRANTY'],
    default: 'VERIFY',
  },
  category: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Category',
    required: true,
  },
}, {
    timestamps: true,
    collection: 'products'
})

productSchema.pre('save', function (next) {
  if(this.installmentAvailable) {
    this.installmentTotalAmount = this.price;
    this.installmentPlans = [];
  }
  next();
});

module.exports = mongoose.model("Product", productSchema);