/**
 * Vendor Model
 * Represents suppliers/vendors (can be registered or open-market)
 */

module.exports = (sequelize, DataTypes) => {
  // Define Vendor model
  const Vendor = sequelize.define('Vendor', {
    // Primary key
    id: {
      type: DataTypes.BIGINT, // Use BIGINT for large scale
      primaryKey: true, // Set as primary key
      autoIncrement: true, // Auto-increment ID
    },
    // Vendor name
    name: {
      type: DataTypes.STRING(150), // Vendor name with max length
      allowNull: false, // Name is required
      validate: {
        notEmpty: true, // Name cannot be empty string
      },
    },
    // Vendor type (registered supplier or open-market supplier)
    type: {
      type: DataTypes.ENUM('OPEN_MARKET', 'REGISTERED'), // Enum for vendor type
      allowNull: false, // Type is required
      validate: {
        isIn: [['OPEN_MARKET', 'REGISTERED']], // Validate enum values
      },
    },
  }, {
    // Model options
    tableName: 'vendors', // 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
  });

  // Define model associations
  Vendor.associate = (models) => {
    // Vendor has many PurchaseOrders (one-to-many relationship)
    Vendor.hasMany(models.PurchaseOrder, {
      foreignKey: 'vendor_id', // Foreign key in PurchaseOrders table
      as: 'purchaseOrders', // Alias for association
    });
    
    // Vendor has many GRNs (one-to-many relationship)
    Vendor.hasMany(models.GRN, {
      foreignKey: 'vendor_id', // Foreign key in GRNs table (if we add it)
      as: 'grns', // Alias for association
    });
  };

  // Return Vendor model
  return Vendor;
};

