module.exports = (sequelize, DataTypes) => {
  const MaterialReturnNoteItem = sequelize.define('MaterialReturnNoteItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    mrn_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'MaterialReturnNote',
        key: 'id'
      }
    },
    material_issue_item_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'MaterialIssueItem',
        key: 'id'
      }
    },
    production_order_component_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'ProductionOrderComponent',
        key: 'id'
      }
    },
    line_number: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Material',
        key: 'id'
      }
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    batch_number: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    lot_number: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    returned_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false
    },
    uom_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'UOM',
        key: 'id'
      }
    },
    return_reason: {
      type: DataTypes.STRING(200),
      allowNull: true
    },
    storage_location: {
      type: DataTypes.STRING(10),
      allowNull: true
    },
    source_storage_location: {
      type: DataTypes.STRING(10),
      allowNull: true,
      comment: 'Source (department) storage location code where stock will be reduced'
    },
    destination_storage_location: {
      type: DataTypes.STRING(10),
      allowNull: true,
      comment: 'Destination (stores) storage location code where stock will be increased'
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'material_return_note_item',
    indexes: [
      { fields: ['mrn_id'] },
      { fields: ['material_id'] },
      { fields: ['material_issue_item_id'] },
      { fields: ['production_order_component_id'] }
    ]
  });

  MaterialReturnNoteItem.associate = function(models) {
    MaterialReturnNoteItem.belongsTo(models.MaterialReturnNote, { foreignKey: 'mrn_id', as: 'mrn' });
    MaterialReturnNoteItem.belongsTo(models.MaterialIssueItem, { foreignKey: 'material_issue_item_id', as: 'materialIssueItem' });
    MaterialReturnNoteItem.belongsTo(models.ProductionOrderComponent, { foreignKey: 'production_order_component_id', as: 'productionOrderComponent' });
    MaterialReturnNoteItem.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    MaterialReturnNoteItem.belongsTo(models.UOM, { foreignKey: 'uom_id', as: 'uom' });
  };

  return MaterialReturnNoteItem;
};

