module.exports = (sequelize, DataTypes) => {
  const SubcontractReceiptItem = sequelize.define('SubcontractReceiptItem', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    subcontract_receipt_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'SubcontractReceipt', key: 'id' }
    },
    subcontract_dc_item_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'SubcontractDCItem', 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
    },
    sent_quantity: {
      type: DataTypes.DECIMAL(18, 3),
      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
    },
    uom_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'UOM', key: 'id' }
    },
    storage_location_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: { model: 'StorageLocation', key: 'id' }
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    }
  }, {
    tableName: 'subcontract_receipt_item',
    indexes: [
      { fields: ['subcontract_receipt_id'] },
      { fields: ['subcontract_dc_item_id'] },
      { fields: ['material_id'] },
      { fields: ['storage_location_id'] },
      { unique: true, fields: ['subcontract_receipt_id', 'line_number'] }
    ]
  });

  SubcontractReceiptItem.associate = function(models) {
    SubcontractReceiptItem.belongsTo(models.SubcontractReceipt, { foreignKey: 'subcontract_receipt_id', as: 'subcontractReceipt' });
    SubcontractReceiptItem.belongsTo(models.SubcontractDCItem, { foreignKey: 'subcontract_dc_item_id', as: 'subcontractDCItem' });
    SubcontractReceiptItem.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    SubcontractReceiptItem.belongsTo(models.UOM, { foreignKey: 'uom_id', as: 'uom' });
    SubcontractReceiptItem.belongsTo(models.StorageLocation, { foreignKey: 'storage_location_id', as: 'storageLocation' });
  };

  return SubcontractReceiptItem;
};
