module.exports = (sequelize, DataTypes) => {
  const MaterialGrade = sequelize.define('MaterialGrade', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    grade_code: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: 'Unique code for material grade (e.g., MS, GI, SS304, SS316, AL)'
    },
    grade_name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: 'Name of material grade (e.g., Mild Steel, Galvanized Iron, Stainless Steel 304)'
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: 'Detailed description of the grade'
    },
    specification: {
      type: DataTypes.STRING(200),
      allowNull: true,
      comment: 'Industry specification (e.g., IS 2062, ASTM A36)'
    },
    properties: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: 'Material properties in JSON format (tensile strength, yield strength, etc.)'
    },
    is_active: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: true
    },
    sort_order: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: 'Display order in dropdowns'
    },
    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: 'material_grade',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'grade_code']
      },
      {
        fields: ['company_id', 'is_active']
      }
    ]
  });

  MaterialGrade.associate = function(models) {
    MaterialGrade.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    MaterialGrade.hasMany(models.Material, { foreignKey: 'grade_id', as: 'materials' });
    MaterialGrade.belongsTo(models.User, { foreignKey: 'created_by', as: 'creator' });
    MaterialGrade.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updater' });
  };

  return MaterialGrade;
};

