module.exports = (sequelize, DataTypes) => {
  const UOMConversion = sequelize.define('UOMConversion', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    from_uom_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'UOM',
        key: 'id'
      }
    },
    to_uom_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'UOM',
        key: 'id'
      }
    },
    conversion_factor: {
      type: DataTypes.DECIMAL(15, 6),
      allowNull: false,
      defaultValue: 1.000000,
      comment: 'Conversion factor: to_uom = from_uom * conversion_factor'
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'Material',
        key: 'id'
      },
      comment: 'NULL for generic conversion, specific material ID for material-specific conversion'
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    effective_from: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    effective_to: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    created_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    },
    updated_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    }
  }, {
    tableName: 'uom_conversion',
    indexes: [
      {
        unique: true,
        fields: ['from_uom_id', 'to_uom_id', 'material_id']
      },
      {
        fields: ['material_id']
      },
      {
        fields: ['status']
      },
      {
        fields: ['effective_from', 'effective_to']
      }
    ]
  });

  UOMConversion.associate = function(models) {
    UOMConversion.belongsTo(models.UOM, { foreignKey: 'from_uom_id', as: 'fromUOM' });
    UOMConversion.belongsTo(models.UOM, { foreignKey: 'to_uom_id', as: 'toUOM' });
    UOMConversion.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
  };

  return UOMConversion;
};

