module.exports = (sequelize, DataTypes) => {
  const SalesReturnItem = sequelize.define('SalesReturnItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    sales_return_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'SalesReturn', key: 'id' }
    },
    line_number: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    invoice_item_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'SalesInvoiceItem', key: 'id' }
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Material', key: 'id' }
    },
    uom_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'UOM', key: 'id' }
    },
    sold_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    already_returned_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    return_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false
    },
    return_reason: {
      type: DataTypes.STRING(200),
      allowNull: true
    },
    warehouse_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'StorageLocation', key: 'id' }
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'sales_return_item',
    indexes: [
      { fields: ['sales_return_id'] },
      { fields: ['invoice_item_id'] },
      { fields: ['material_id'] }
    ]
  });

  SalesReturnItem.associate = function(models) {
    SalesReturnItem.belongsTo(models.SalesReturn, { foreignKey: 'sales_return_id', as: 'salesReturn' });
    SalesReturnItem.belongsTo(models.SalesInvoiceItem, { foreignKey: 'invoice_item_id', as: 'invoiceItem' });
    SalesReturnItem.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    SalesReturnItem.belongsTo(models.UOM, { foreignKey: 'uom_id', as: 'uom' });
    SalesReturnItem.belongsTo(models.StorageLocation, { foreignKey: 'warehouse_id', as: 'warehouse' });
  };

  return SalesReturnItem;
};
