module.exports = (sequelize, DataTypes) => {
  const PurchaseReturnItem = sequelize.define('PurchaseReturnItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    purchase_return_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'PurchaseReturn', key: 'id' }
    },
    line_number: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    grn_item_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'GoodsReceiptNoteItem', key: 'id' }
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'Material', key: 'id' }
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: 'Full material line spec (e.g. thickness × grade × L × W), aligned with GRN line'
    },
    uom_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'UOM', key: 'id' }
    },
    received_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
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'purchase_return_item',
    indexes: [
      { fields: ['purchase_return_id'] },
      { fields: ['grn_item_id'] },
      { fields: ['material_id'] }
    ]
  });

  PurchaseReturnItem.associate = function(models) {
    PurchaseReturnItem.belongsTo(models.PurchaseReturn, { foreignKey: 'purchase_return_id', as: 'purchaseReturn' });
    PurchaseReturnItem.belongsTo(models.GoodsReceiptNoteItem, { foreignKey: 'grn_item_id', as: 'grnItem' });
    PurchaseReturnItem.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    PurchaseReturnItem.belongsTo(models.UOM, { foreignKey: 'uom_id', as: 'uom' });
  };

  return PurchaseReturnItem;
};

