module.exports = (sequelize, DataTypes) => {
  const QAMaster = sequelize.define('QAMaster', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Company', key: 'id' }
    },
    plant_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Plant', key: 'id' }
    },
    operation_name_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'OperationName', key: 'id' }
    },
    operation_no: { type: DataTypes.INTEGER, allowNull: true },
    bom_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'BOMHeader', key: 'id' }
    },
    item_material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Material', key: 'id' }
    },
    qa_menus: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: 'JSON array of selected QA menu keys'
    },
    powder_coating_grade_ids: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: 'JSON array of selected powder coating grade material IDs'
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    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: 'qa_master',
    underscored: true,
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      { fields: ['company_id'] },
      { fields: ['plant_id'] },
      { fields: ['operation_name_id'] },
      { fields: ['bom_id'] },
      { fields: ['item_material_id'] },
      { fields: ['status'] }
    ]
  });

  QAMaster.associate = function(models) {
    QAMaster.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    QAMaster.belongsTo(models.Plant, { foreignKey: 'plant_id', as: 'plant' });
    QAMaster.belongsTo(models.OperationName, { foreignKey: 'operation_name_id', as: 'operationName' });
    QAMaster.belongsTo(models.BOMHeader, { foreignKey: 'bom_id', as: 'bom' });
    QAMaster.belongsTo(models.Material, { foreignKey: 'item_material_id', as: 'itemMaterial' });
    QAMaster.hasMany(models.QAMasterComponent, { foreignKey: 'qa_master_id', as: 'components' });
    QAMaster.belongsTo(models.User, { foreignKey: 'created_by', as: 'createdByUser' });
    QAMaster.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updatedByUser' });
  };

  return QAMaster;
};

