module.exports = (sequelize, DataTypes) => {
  const MaterialSupplier = sequelize.define('MaterialSupplier', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Material',
        key: 'id'
      },
      comment: 'Reference to Material'
    },
    vendor_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'BusinessPartner',
        key: 'id'
      },
      comment: 'Reference to BusinessPartner (Vendor)'
    },
    vendor_material_number: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: 'Material number as per vendor catalog'
    },
    vendor_material_description: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: 'Material description as per vendor'
    },
    is_preferred: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      comment: 'Is this the preferred vendor for this material'
    },
    lead_time_days: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: 'Lead time in days for procurement from this vendor'
    },
    minimum_order_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: true,
      comment: 'Minimum order quantity from this vendor'
    },
    standard_price: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: true,
      comment: 'Standard price from this vendor'
    },
    currency_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'Currency',
        key: 'id'
      },
      comment: 'Currency for the standard price'
    },
    validity_from: {
      type: DataTypes.DATEONLY,
      allowNull: true,
      comment: 'Price validity start date'
    },
    validity_to: {
      type: DataTypes.DATEONLY,
      allowNull: true,
      comment: 'Price validity end date'
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'material_supplier',
    indexes: [
      {
        unique: true,
        fields: ['material_id', 'vendor_id'],
        name: 'unique_material_vendor'
      },
      {
        fields: ['material_id']
      },
      {
        fields: ['vendor_id']
      },
      {
        fields: ['is_preferred']
      }
    ]
  });

  MaterialSupplier.associate = function(models) {
    MaterialSupplier.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    MaterialSupplier.belongsTo(models.BusinessPartner, { foreignKey: 'vendor_id', as: 'vendor' });
    MaterialSupplier.belongsTo(models.Currency, { foreignKey: 'currency_id', as: 'currency' });
  };

  return MaterialSupplier;
};

