module.exports = (sequelize, DataTypes) => {
  const PurchaseRequisitionItem = sequelize.define('PurchaseRequisitionItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    pr_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'PurchaseRequisition',
        key: 'id'
      }
    },
    line_number: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Material',
        key: 'id'
      }
    },
    material_number: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: 'Material / part number for the line (may match Material Master or MR nesting)'
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false
    },
    uom_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'UOM',
        key: 'id'
      }
    },
    unit_price: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: true
    },
    estimated_amount: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0
    },
    required_date: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    gross_required_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: true,
      comment: 'Gross required quantity from MRP (before deducting available stock)'
    },
    available_stock_at_pr_creation: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: true,
      comment: 'Available stock at the time of PR creation (for reference)'
    },
    line_weight_kg: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: true,
      comment: 'Total line weight in KG at transaction time'
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'purchase_requisition_item',
    indexes: [
      {
        fields: ['pr_id']
      },
      {
        fields: ['material_id']
      }
    ]
  });

  PurchaseRequisitionItem.associate = function(models) {
    PurchaseRequisitionItem.belongsTo(models.PurchaseRequisition, { foreignKey: 'pr_id', as: 'purchaseRequisition' });
    PurchaseRequisitionItem.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    PurchaseRequisitionItem.belongsTo(models.UOM, { foreignKey: 'uom_id', as: 'uom' });
  };

  return PurchaseRequisitionItem;
};

