module.exports = (sequelize, DataTypes) => {
  const GeneralReceiptItem = sequelize.define('GeneralReceiptItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    general_receipt_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'GeneralReceipt', key: 'id' }
    },
    general_dc_item_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'GeneralDCItem', key: 'id' }
    },
    line_number: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    machine_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'Machine', key: 'id' }
    },
    machine_work: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    sent_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    unit_price: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0
    },
    line_total: {
      type: DataTypes.DECIMAL(18, 2),
      allowNull: false,
      defaultValue: 0
    },
    received_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    rejection_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      allowNull: false,
      defaultValue: 0
    },
    storage_location_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'StorageLocation', key: 'id' }
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'general_receipt_item',
    indexes: [
      { fields: ['general_receipt_id'] },
      { fields: ['general_dc_item_id'] },
      { fields: ['machine_id'] },
      { fields: ['storage_location_id'] },
      { unique: true, fields: ['general_receipt_id', 'line_number'] }
    ]
  });

  GeneralReceiptItem.associate = function(models) {
    GeneralReceiptItem.belongsTo(models.GeneralReceipt, { foreignKey: 'general_receipt_id', as: 'generalReceipt' });
    GeneralReceiptItem.belongsTo(models.GeneralDCItem, { foreignKey: 'general_dc_item_id', as: 'generalDCItem' });
    GeneralReceiptItem.belongsTo(models.Machine, { foreignKey: 'machine_id', as: 'machine' });
    GeneralReceiptItem.belongsTo(models.StorageLocation, { foreignKey: 'storage_location_id', as: 'storageLocation' });
  };

  return GeneralReceiptItem;
};
