const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  companyId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company',
    required: true
  },
  productCode: {
    type: String,
    required: true,
    unique: true,
    uppercase: true,
    trim: true
  },
  name: {
    type: String,
    required: [true, 'Product name is required'],
    trim: true
  },
  description: {
    type: String,
    trim: true
  },
  category: {
    type: String,
    required: true,
    trim: true
  },
  subCategory: {
    type: String,
    trim: true
  },
  brand: {
    type: String,
    trim: true
  },
  sku: {
    type: String,
    trim: true,
    unique: true,
    sparse: true
  },
  barcode: {
    type: String,
    trim: true
  },
  pricing: {
    cost: {
      type: Number,
      default: 0
    },
    price: {
      type: Number,
      required: [true, 'Price is required'],
      min: 0
    },
    salePrice: {
      type: Number,
      min: 0
    },
    currency: {
      type: String,
      default: 'INR'
    },
    taxRate: {
      type: Number,
      default: 0
    }
  },
  inventory: {
    trackInventory: {
      type: Boolean,
      default: true
    },
    quantity: {
      type: Number,
      default: 0,
      min: 0
    },
    minStockLevel: {
      type: Number,
      default: 5
    },
    maxStockLevel: {
      type: Number,
      default: 100
    },
    unit: {
      type: String,
      default: 'piece'
    }
  },
  dimensions: {
    weight: Number,
    length: Number,
    width: Number,
    height: Number,
    unit: {
      type: String,
      default: 'cm'
    }
  },
  images: [{
    url: String,
    alt: String,
    isPrimary: {
      type: Boolean,
      default: false
    }
  }],
  specifications: {
    type: Map,
    of: String
  },
  tags: [String],
  status: {
    type: String,
    enum: ['active', 'inactive', 'discontinued', 'out_of_stock'],
    default: 'active'
  },
  isPublished: {
    type: Boolean,
    default: true
  },
  isFeatured: {
    type: Boolean,
    default: false
  },
  supplier: {
    name: String,
    contact: String,
    email: String
  },
  warranty: {
    duration: Number,
    unit: {
      type: String,
      enum: ['days', 'months', 'years'],
      default: 'months'
    },
    terms: String
  },
  metadata: {
    views: {
      type: Number,
      default: 0
    },
    sales: {
      type: Number,
      default: 0
    },
    rating: {
      type: Number,
      default: 0,
      min: 0,
      max: 5
    },
    reviews: {
      type: Number,
      default: 0
    }
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
}, {
  timestamps: true
});

// Generate product code before saving
productSchema.pre('save', async function(next) {
  if (!this.isNew) return next();
  
  const Company = mongoose.model('Company');
  const company = await Company.findById(this.companyId);
  const count = await this.constructor.countDocuments({ companyId: this.companyId });
  
  this.productCode = `PRD-${company.code}-${String(count + 1).padStart(5, '0')}`;
  next();
});

// Indexes
productSchema.index({ companyId: 1, status: 1 });
productSchema.index({ productCode: 1 });
productSchema.index({ sku: 1 });
productSchema.index({ category: 1, subCategory: 1 });
productSchema.index({ name: 'text', description: 'text', tags: 'text' });

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