module.exports = (sequelize, DataTypes) => {
  const MeasuringInstrumentHistoryCard = sequelize.define('MeasuringInstrumentHistoryCard', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'Company', key: 'id' }
    },
    history_card_no: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    card_date: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    instrument_description: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    least_count: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    serial_number: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    identification_number: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    location: {
      type: DataTypes.STRING(200),
      allowNull: true
    },
    make: {
      type: DataTypes.STRING(200),
      allowNull: true
    },
    range: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    date_of_incorporation: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    error_limit_1: {
      type: DataTypes.DECIMAL(15, 5),
      allowNull: true
    },
    error_limit_2: {
      type: DataTypes.DECIMAL(15, 5),
      allowNull: true
    },
    error_limit_3: {
      type: DataTypes.DECIMAL(15, 5),
      allowNull: true
    },
    calibration_plan: {
      type: DataTypes.STRING(500),
      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: 'measuring_instrument_history_card',
    underscored: true,
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      { fields: ['company_id'] },
      { fields: ['history_card_no'] },
      { fields: ['card_date'] }
    ]
  });

  MeasuringInstrumentHistoryCard.associate = function(models) {
    MeasuringInstrumentHistoryCard.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    MeasuringInstrumentHistoryCard.belongsTo(models.User, { foreignKey: 'created_by', as: 'creator' });
    MeasuringInstrumentHistoryCard.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updater' });
    MeasuringInstrumentHistoryCard.hasMany(models.MeasuringInstrumentHistoryCardDetail, { foreignKey: 'history_card_id', as: 'details' });
  };

  return MeasuringInstrumentHistoryCard;
};
