/**
 * Inventory Model
 * Quantity-based inventory tracking (Layer 1 of dual inventory model)
 */

module.exports = (sequelize, DataTypes) => {
  // Define Inventory model
  const Inventory = sequelize.define('Inventory', {
    // Primary key
    id: {
      type: DataTypes.BIGINT, // Use BIGINT for large scale
      primaryKey: true, // Set as primary key
      autoIncrement: true, // Auto-increment ID
    },
    // Foreign key to Product
    product_id: {
      type: DataTypes.BIGINT, // Match Product ID type
      allowNull: false, // Product ID is required
      references: {
        model: 'products', // Reference to products table
        key: 'id', // Reference to id column
      },
      onUpdate: 'CASCADE', // Cascade update on product update
      onDelete: 'CASCADE', // Cascade delete when product is deleted
    },
    // Current quantity in stock
    quantity: {
      type: DataTypes.DECIMAL(12, 3), // Decimal with 12 digits, 3 decimal places (supports fractional quantities)
      defaultValue: 0, // Default quantity is 0
      allowNull: false, // Quantity is required
      validate: {
        min: 0, // Quantity cannot be negative
      },
    },
    // Reorder level - alert when stock falls below this
    reorder_level: {
      type: DataTypes.DECIMAL(12, 3), // Decimal with 12 digits, 3 decimal places
      defaultValue: 0, // Default reorder level is 0
      allowNull: false, // Reorder level is required
      validate: {
        min: 0, // Reorder level cannot be negative
      },
    },
  }, {
    // Model options
    tableName: 'inventories', // Explicit table name
    underscored: true, // Use snake_case for database columns
    timestamps: true, // Enable createdAt and updatedAt timestamps
    createdAt: 'created_at', // Map createdAt to created_at column
    updatedAt: 'updated_at', // Map updatedAt to updated_at column
    indexes: [
      // Unique index on product_id (one inventory record per product)
      {
        unique: true, // Unique constraint
        fields: ['product_id'], // Index on product_id field
      },
    ],
  });

  // Define model associations
  Inventory.associate = (models) => {
    // Inventory belongs to Product (many-to-one relationship)
    Inventory.belongsTo(models.Product, {
      foreignKey: 'product_id', // Foreign key in Inventory table
      as: 'product', // Alias for association
    });
  };

  // Return Inventory model
  return Inventory;
};

